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

Posted

技术标签:

【中文标题】为 Lambda 代理集成启用 CORS 支持的问题【英文标题】:Issues enabling CORS support for Lambda proxy integrations 【发布时间】: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(`$baseURLuser/$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 不,没有附加资源策略。它确实适用于失眠。 【参考方案1】:

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

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

【讨论】:

以上是关于为 Lambda 代理集成启用 CORS 支持的问题的主要内容,如果未能解决你的问题,请参考以下文章

使用代理集成时,API 网关和 Lambda 出现 CORS 错误**仅**

API GW Lambda 代理集成 CORS 问题

如何重用 CORS 预检和资源请求之间的连接?

放大:即使在 API 网关和 Lambda 标头中启用了 CORS,但 CORS 标头“Access-Control-Allow-Origin”缺失错误

在 AWS API 上启用了 CORS,但在 Angular 中仍然获得“No Access-Control-Allow-Origin”

我在 NEST.JS LAMBDA PROXY 应用程序上收到 CORS 错误