API网关无法启用CORS

wll*_*kle 2 javascript amazon-web-services reactjs aws-amplify aws-cdk

当我尝试从我的 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
Run Code Online (Sandbox Code Playgroud)

我使用CDK定义的API资源都传递到这个方法中

Win*_*jam 8

就像这里解释的那样,您需要在 API Gateway 中启用 CORS,您还需要Access-Control-Allow-Origin从 Lambda 返回标头,因为 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
}
Run Code Online (Sandbox Code Playgroud)