【发布时间】:2021-05-18 06:05:05
【问题描述】:
我正在使用 react.js 应用程序调用 API。我从 AWS API Gateway 收到有关 CORS 策略的错误:
CORS 策略已阻止从源“http://localhost:3000”访问“https://awsapigatewayid.execute-api.ap-south-1.amazonaws.com/staging/top10”处的 XMLHttpRequest:预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 access-control-allow-origin。
来自调用 api 的 React App 代码,例如:
let options = {
url: `https://awsapigatewayid.execute-api.ap-south-1.amazonaws.com/staging/top10`,
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Req-Time': getCurrentTimestamp(),
'Access-Control-Allow-Origin': '*',
},
data: data || {},
};
if (isAuthorised) {
options.headers['X-Auth-Token'] = 'usertokengoeshere';
}
const response = await axios(options);
我的来自 AWS API Gateway 的 API:
【问题讨论】:
-
这不是 API Gateway 错误,而是您的浏览器阻止了请求。为什么要在请求中放置
Access-Control-Allow-Origin标头?参见例如docs.aws.amazon.com/apigateway/latest/developerguide/… 了解更多信息。
标签: amazon-web-services aws-lambda aws-api-gateway