javascript - 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 资源都传入这个方法
解决方案
就像在此处解释的那样,您需要在 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
}
推荐阅读
- android - 以编程方式更改约束布局的边距
- vue.js - 使用 Webpacker 从 Rails 5 中的子路径提供 Vue.js 应用程序
- java - 使用 AutoCompleteTextView 清除自动完成
- powershell - 如何从 foreach 并行 Powershell 存储值
- vba - ms 使用其他形式的字符串访问 VBA?
- mongodb - 获取当年的总营业额 --- 不是过去 365 天的总营业额
- javascript - 如何在Javascript中将键:“值”转换为键:[“值”]?
- java - 是否需要在带有 Spring Boot 的微服务架构项目上使用 ManyToOne/OneToMany 注释?
- excel - Excel 数据透视表计算字段未按预期运行
- python - 非法硬件指令导入 tensorflow。MacBook M1