amazon-web-services - 为什么 AWS Lambda、API Gateway 返回 CORS 错误
问题描述
我知道这个问题已经在网络上的许多帖子中有所提及,我想我已经尝试了所有这些,但我的本地反应应用程序仍然收到 403 CORS 错误。
以下是来自开发工具的部分标题:
#GENERAL:
Request URL: https://<myGatewayApiUrl>.amazonaws.com/dev/api/byid/1/129
Request Method: OPTIONS
Status Code: 403
#RESPONSE HEADERS
access-control-allow-headers: Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token
access-control-allow-methods: GET,OPTIONS
access-control-allow-origin: *
content-length: 42
content-type: application/json
我一直在 API Gateway 设置中工作Enable CORS
,但是我得到一个 get 方法的错误Add Access-Control-Allow-Origin Integration Response Header Mapping to GET method
-> invalid response status code specified
- 但是设置了 OPTIONS 标头并且设置了 GET 标头Access-Control-Allow-Origin
。
我正在使用 express 和 cors 包,这是我的 API index.js 文件中的一个片段:
const app = express();
app.use(cors());
app.options('*', cors());
这是来自 React 应用程序的请求代码:
export const getRecordById = async (userId, id, token) => {
try {
const response = await axios.get(
process.env.REACT_APP_API_URL + `/byid/${userId}/${id}`,
{
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
}
);
return response.data;
} catch (error) {
console.log('ERROR', error);
return error;
}
};
这是我来自 Lambda API 的响应代码:
getById: asyncHandler(async (req, res, next) => {
const { user, id } = req.params;
const result = await recordsService.getRecordById(user, id);
res.set({
'content-type': 'application/json',
'Access-Control-Allow-Origin': '*',
});
if (!result) {
res.status(400).json({
error: true,
message: 'get record by ID action failed',
data: {},
});
}
res.status(200).json({
error: false,
message: 'successful record retrieval',
data: {
record: result,
},
});
}),
另外,我的 serverless.yml 文件 http 事件设置如下:(据我了解cors: true
应该处理预检请求)
- http:
path: /api/records/byid/{user}/{id}
method: GET
cors: true
我花了太多时间试图弄清楚这一点。它一定是简单而愚蠢的东西,我使用res.set()
正确吗?一切看起来都是正确的,我知道我错过了一些东西。谢谢
解决方案
默认情况下,如果找不到 URL,API Gateway 将拒绝调用并返回 CORS 错误。
看起来 Axios 缺少/records
请求 URL 中的位。
推荐阅读
- python - 在 Pycharm 上使用 Pyttsx3 模块的文本到语音期间没有获得任何音频输出
- python - re.search 获取所有子块
- laravel - Vue / Laravel / Vuetify - 在数组中附加多个文件
- sum - 通过预设的 N 个观测值对变量求和
- vue.js - 基本输入隐藏文本而不是在字段内显示它
- sql - 在sql中选择限制
- python - Python从迭代源创建字典列表
- python - openpyxl:文件之间的校验和不匹配,但种子数据相同
- swift - 快速访问文本字段的值时出现奇怪的错误
- java - 为什么此代码不断返回“变量可能尚未初始化”错误?