26

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

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

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

4

5 回答 5

48

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

于 2017-07-03T18:29:32.127 回答
8

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

如果您不想通过 处理CORS请求Lambda,请尝试更改您的设置以在级别Lambda Method上处理。CORSAPI Gateway

这是在 AWS API Gateway 上设置 CORS的详细官方教程。

X-Api-Key允许标头进入也很重要,Access-Control-Allow-Headers否则身份验证将不起作用,并且会出现错误。

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

于 2015-08-10T20:10:47.163 回答
3

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

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

于 2020-08-08T15:37:26.313 回答
2

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

于 2015-08-19T09:45:49.880 回答
0

我有一个使用 ANY 方法的 HTTP API Gateway 解决方案。如果您在任何方法上使用授权方,您的授权方将拒绝 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)
}

这对我有用。

于 2022-02-02T13:03:45.377 回答