【发布时间】:2020-09-05 21:00:48
【问题描述】:
我有一个通过 API Gateway 公开的 lambda 函数。我正在使用 axios 调用该函数。我没有使用 OPTIONS 方法在 API Gateway 上启用 cors,因为我正在使用 lambda 代理集成,所以我在我的 lambda 函数中发回响应标头。它适用于失眠,但在浏览器上我收到 {message: disabled} 和以下错误。
[Error] Preflight response is not successful
[Error] XMLHttpRequest cannot load https://xxxxxxxxx.execute-api.us-east-2.amazonaws.com/production/user/xxxxxxxxxxxxx due to access control checks.
[Error] Failed to load resource: Preflight response is not successful (xxxxxxxxxxxxxxx, line 0)
[Error] Unhandled Promise Rejection: Error: Network Error
(anonymous function)
promiseReactionJob
AXIOS 函数
import axios from "axios";
const baseURL =
"https://xxxxxxxxxx.execute-api.us-east-2.amazonaws.com/production/";
import * as apiKey from "./apiConfig";
export const getUser = (username) => {
return axios
.get(`${baseURL}user/${username}`, {
headers: {
"x-api-key": apiKey
},
})
.then(({ data }) => {
console.log(data);
});
};
Lambda 函数返回
const response = {
statusCode: 200,
body: JSON.stringify(data.Item),
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
};
return response;
编辑 根据建议,我在 API Gateway 上启用了 CORS,它使用以下标头和标头映射创建了 OPTIONS 方法。上述预检响应错误消失了。相反,我现在在下面收到此错误。我还想注意 OPTIONS 方法的 Api Key Required 设置为 false,但是当我将其设置为 true 时,我再次收到上述错误。
{message: forbidden}
https://xxxxxxxxxxxxx.execute-api.us-east-2.amazonaws.com/production/user/xxxxxxxxxxxxxxxxxx
[Error] Failed to load resource: the server responded with a status of 403 () (xxxxxxxxxxxxxxxxxxxxxxx, line 0)
Unhandled Promise Rejection: Error: Request failed with status code 403
Access-Control-Allow-Headers : 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'
Access-Control-Allow-Methods : 'DELETE,GET,OPTIONS,PATCH'
Access-Control-Allow-Origin : '*'
【问题讨论】:
-
PreFlight 使用
OPTIONS方法。如果您忽略它,这可能会解释您的错误。 -
@Marcin 感谢您回答我的问题。我使用 OPTIONS 在 API Gateway 上重新启用了 CORS,但仍然收到错误消息?见编辑
-
您是否将策略附加到您的 lambda 函数以允许 API Gateway 实际调用它?
-
@tpschmidt 不,没有附加资源策略。它确实适用于失眠。
标签: amazon-web-services aws-lambda axios cors aws-api-gateway