在AWS Lambda上配置CORS响应头?

时间:2015-08-10 05:00:28

标签: amazon-web-services cors aws-lambda aws-api-gateway

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

问题是AWS API Gateway不提供配置CORS标头的本机方式。

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

4 个答案:

答案 0 :(得分:19)

如果启用了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

答案 1 :(得分:6)

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

如果您不希望CORS处理Lambda次请求,请尝试更改Lambda Method的设置以处理CORS级别的API Gateway

以下是CORS setup on AWS API Gateway的详细官方教程。

X-Api-Key中允许标题Access-Control-Allow-Headers也很重要,否则auth将无效,您将收到错误。

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

答案 2 :(得分:1)

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

答案 3 :(得分:1)

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

...
    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