【问题标题】:API Gateway failing to enable CORSAPI 网关无法启用 CORS
【发布时间】:2019-08-18 19:58:43
【问题描述】:

当我尝试从我的 react 应用请求一个 lambda 支持的 API(使用 API 网关,使用 CLI 和云开发工具包部署)时,我收到以下错误:

Access to XMLHttpRequest at 'https://xxxxxxxxxx.execute-api.eu-west-1.amazonaws.com/prod/xxxxx' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

GET https://xxxxxxxxxx.execute-api.eu-west-1.amazonaws.com/prod/xxxxx net::ERR_FAILED

我使用CDK定义的API资源全部传入this method

【问题讨论】:

  • 这似乎是一个愚蠢的问题,但是您是否在 API Gateway 中启用了 CORS 并重新部署了 API?
  • @danimal 是的,我已经尝试过了,但问题是 CDK 应该已经处理好了。
  • 您能否提供用于部署 API 的 CDK 代码的 sn-p?

标签: javascript reactjs amazon-web-services aws-amplify aws-cdk


【解决方案1】:

就像解释 here 一样,您需要在 API Gateway 中启用 CORS,但是您还需要从 Lambda 返回一个 Access-Control-Allow-Origin 标头,因为 API Gateway 不会自动将其添加到回复。

这是我的 Lambda 为简单的 Get 返回的示例:

return {
  headers,
  body: JSON.stringify(response.Item),
  statusCode: 200
};

const headers = {
  "Access-Control-Allow-Origin": "*", // Required for CORS support to work
  "Access-Control-Allow-Credentials": true // Required for cookies, authorization headers with HTTPS
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-19
    • 2017-12-16
    • 2018-01-30
    • 2019-03-16
    • 2015-02-19
    • 2020-12-09
    • 2017-07-09
    • 2020-07-04
    相关资源
    最近更新 更多