gpt4 book ai didi

aws-lambda - 被 CORS 阻止,也无法使用 Amplify Functions 访问 REST API 端点

转载 作者:行者123 更新时间:2023-12-04 04:00:50 25 4
gpt4 key购买 nike

我正在访问此链接以部署具有 Amplify Functions 的 Apollo GraphQL 服务器: https://dev.to/aws/10-minute-tutorial-deploy-an-apollo-graphql-server-with-amplify-functions-38p1

但是,当我运行“npm start”时,它无法访问“http://localhost:3000”,显示:

Access to fetch at 'https://******.execute-api.us-east-1.amazonaws.com/dev/graphql' 
from origin 'http://localhost:3000' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested resource. If an
opaque response serves your needs, set the request's mode to 'no-cors' to fetch
the resource with CORS disabled.
Failed to load resource: net::ERR_FAILED   
******.execute-api.us-east-1.amazonaws.com/dev/graphql:1

这是我在 index.js 中为 Lambda 设置导出处理程序的方法:

exports.handler = server.createHandler({
cors: {
origin: "*",
credentials: true, // I tried setting false is also the same
},
});

我不确定 CORS 是否是根本原因,因为我认为上面的配置应该可以让它工作。我怀疑 API 端点出了问题。我看到使用浏览器访问 REST API 端点失败,这是 aws-exports.js 中的链接:

awsmobile.aws_cloud_logic_custom[0] = "******.execute-api.us-east-1.amazonaws.com/dev"

显示:

{"message":"Missing Authentication Token"}

我也无法访问“******.execute-api.us-east-1.amazonaws.com/dev/graphql”,显示:

{"message": "Internal server error"}

是因为缺少 AWS 签名吗?我还需要为身份验证配置什么吗?

最佳答案

用了几天时间,找到了根本原因。这既不是 CORS 也不是身份验证问题。

根据 https://docs.aws.amazon.com/apigateway/latest/developerguide/amazon-api-gateway-using-stage-variables.html ,预计会看到“缺少身份验证 token ”,因为我将访问子资源而不是端点本身。这里的子资源是“******.execute-api.us-east-1.amazonaws.com/dev/graphql”。

The Invoke URL link points to the root resource of the API in its betastage. Navigating to the URL by choosing the link calls the beta stageGET method on the root resource. If methods are defined on childresources and not on the root resource itself, choosing the Invoke URLlink returns a {"message":"Missing Authentication Token"} errorresponse. In this case, you must append the name of a specific childresource to the Invoke URL link.

为什么它无法访问“******.execute-api.us-east-1.amazonaws.com/dev/graphql”,我通过检查CloudWatch日志发现了那个错误。这是一个很好的调试工具。

    "stack": [
"Runtime.ImportModuleError: Error: Cannot find module 'apollo-server-lambda'",

“amplify push”无法识别这个包,因为我使用的是节点 v6.9.5 的终端。将其更新到最新节点并“放大推送”后,问题就解决了。

CORS 错误令人分心,在解决上述问题后它不会出现。不会添加 CORS header ,因为 index.js 编译失败。

关于aws-lambda - 被 CORS 阻止,也无法使用 Amplify Functions 访问 REST API 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63065300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com