在 AWS Lambda 上配置 CORS 响应标头?

问题描述 投票:0回答:5

我正在尝试使用 AWS API Gateway 创建新服务,但我发现浏览器会自动调用 OPTIONS 方法以获取 CORS 信息。

问题在于 AWS API Gateway 不提供配置 CORS 标头的本机方法。

是否可以创建 Lambda 脚本来响应 OPTIONS 方法?

amazon-web-services cors aws-lambda aws-api-gateway
5个回答
56
投票

如果启用了 lambda-proxy,则需要手动设置 CORS 标头:

module.exports.hello = function(event, context, callback) {

    const response = {
      statusCode: 200,
      headers: {
        "Access-Control-Allow-Origin" : "*", // Required for CORS support to work
        "Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
      },
      body: JSON.stringify({ "message": "Hello World!" })
    };

    callback(null, response);
};

https://serverless.com/framework/docs/providers/aws/events/apigateway#enabling-cors


10
投票

如果您使用

{proxy+}
端点,则必须在 Lambda 函数中处理 CORS HTTP 请求。实现取决于您使用的框架。对于 Express,最简单的解决方案就是使用 Express CORS 中间件

如果您不想处理

CORS
Lambda
请求,请尝试更改
Lambda Method
的设置以在
CORS
级别处理
API Gateway

这里有关于 AWS API Gateway 上的 CORS 设置的详细官方教程

同样重要的是,您允许在

X-Api-Key
中使用标头
Access-Control-Allow-Headers
,否则身份验证将无法工作,并且您会收到错误。

编辑: 2015 年 11 月,API 网关团队添加了一项新功能来简化 CORS 设置。


5
投票

这是一个示例,希望对您有所帮助:

...
    return {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "*", // Allow from anywhere 
            "Access-Control-Allow-Methods": "GET" // Allow only GET request 
        },
        body: JSON.stringify(response)
    }
}

欲了解更多信息,请查看此链接: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html


2
投票

如果您使用 JQuery $.ajax,它将在 OPTIONS 请求之后发送带有 POST 的 X-Requested-With,因此您需要确保在 AWS API 上设置 OPTIONS access-control-accept-headers 时包含该标头:X-Requested-With 以及其他标头。


0
投票

我有一个使用任何方法的 HTTP API 网关解决方案。 如果您在任何方法上使用授权者,您的授权者将拒绝 OPTIONS 请求,因为它不包含授权/承载令牌。 解决方案很简单: 在 ANY 路由旁边,使用完全相同的路径创建 OPTIONS 路由,但没有授权者,指向 lambda 函数。然后在 lambda 中添加

const headers = {
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "*",
    "Cache-Control": "max-age=0, no-store, must-revalidate",
    Pragma: "no-cache",
    Expires: 0
};
data = {
        multiValueHeaders: {},
        isBase64Encoded: false,
        statusCode: 200,
        headers: headers,
        body: ""
    }
if (event.httpMethod == "OPTIONS") {
    return context.done(undefined, data)
}

这对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.