首页 > 解决方案 > API 网关无法启用 CORS

问题描述

当我尝试从我的 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 资源都传入这个方法

标签: javascriptreactjsamazon-web-servicesaws-amplifyaws-cdk

解决方案


就像在此处解释的那样,您需要在 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
}

推荐阅读