aws-lambda - 被 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 签名吗?我还需要为身份验证配置什么吗?
解决方案
用了几天,找到了根本原因。这既不是 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 无法编译。
推荐阅读
- android - Braintree Drop-in UI:错误:无法解决:org.jfrog.cardinalcommerce.gradle:cardinalmobilesdk:2.2.1-2?
- if-statement - 谷歌电子表格有条件加入
- stripe-payments - 在 Zapier 中使用自定义请求创建 Stripe 退款
- postgresql - Postgres UPDATE:列名的混淆值
- java - DBRider 没有在新的测试类运行之前清理数据,我该如何解决这个问题?
- python - 将字符串转换为带有模式的几个变量
- c# - 列加载事件以设置子级边距
- ffmpeg - ffmpeg 到 Youtube Live 停止工作。ffmpeg 继续运行
- html - 将禁用属性传递给子组件中的 HTML 元素不起作用
- intellij-idea - 带有@GrailsCompileStatic 注解的Grails GORM 类在静态映射闭包表、版本、autoTimestamp 中显示为未解析符号