我知道这个问题已经在网络上的很多帖子中讨论了,我想我都尝试过了,但是我的本地React应用仍然收到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网关中设置Enable CORS
,但是我遇到了一个get方法的错误Add Access-Control-Allow-Origin Integration Response Header Mapping to GET method
-> invalid response status code specified
-但是设置了OPTIONS标头,Access-Control-Allow-Origin
却设置了GET标头。
我正在使用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中的位。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句