启用 CORS 支持 Lambda 代理集成的问题



我有一个通过API网关公开的lambda函数。我正在用 axios 调用该函数。我没有使用 OPTIONS 方法在 API 网关上启用 cors,因为我使用的是 lambda 代理集成,所以我在我的 lambda 函数中发回响应标头。它适用于失眠,但在浏览器上我收到{消息:禁止}和下面的错误。

[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

公理函数

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 网关上启用了 CORS,该网关使用以下标头和标头映射创建了 OPTIONS 方法。上述预检响应错误消失。相反,我现在在下面收到此错误。我还想注意 OPTIONS 方法的 Api 密钥必需设置为 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 : '*'

我最终启用了 CORS,重新部署了 API 网关并将所有标头设置为下面的 lambda 函数。它没有立即工作,但在部署后一段时间后。

const response = {
statusCode: 200,
body: JSON.stringify(data.Item),
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
};
return response;

最新更新