首页 > 解决方案 > 被 CORS 阻止并且也无法使用 Amplify Functions 访问 REST API 端点

问题描述

我正在按照此链接部署具有放大功能的 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 签名吗?我还需要为身份验证配置什么吗?

标签: aws-lambdaaws-api-gatewayaws-amplifyapollo-server

解决方案


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

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

Invoke URL 链接指向处于测试阶段的 API 的根资源。通过选择链接导航到 URL 会调用根资源上的 beta 阶段 GET 方法。如果方法是在子资源而不是根资源本身上定义的,则选择 Invoke URL 链接会返回 {"message":"Missing Authentication Token"} 错误响应。在这种情况下,您必须将特定子资源的名称附加到调用 URL 链接。

对于无法访问“******.execute-api.us-east-1.amazonaws.com/dev/graphql”的原因,我通过查看 CloudWatch 日志发现了该错误。它是一个很好的调试工具。

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

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

CORS 错误让人分心,修复上述问题后不会出现。不会添加 CORS 标头,因为 index.js 无法编译。


推荐阅读