我正在尝试使用AWS API Gateway创建新的服务,但我发现浏览器会自动调用OPTIONS方法以获取CORS信息。
问题是AWS API Gateway没有提供本地配置CORS标头的方式。
是否可以创建Lambda脚本以响应OPTIONS方法?
我正在尝试使用AWS API Gateway创建新的服务,但我发现浏览器会自动调用OPTIONS方法以获取CORS信息。
问题是AWS API Gateway没有提供本地配置CORS标头的方式。
是否可以创建Lambda脚本以响应OPTIONS方法?
如果您启用了 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
{proxy+}
端点,则必须在 Lambda 函数中处理 CORS HTTP 请求。实现取决于您使用的框架。对于 Express 框架,最简单的解决方案是直接使用 Express CORS 中间件。CORS
请求,请尝试更改您的 Lambda 方法
设置来处理 API Gateway
层面上的 CORS
。Access-Control-Allow-Headers
中包含标头 X-Api-Key
,否则认证将无法正常工作并且会出现错误。
编辑: 在2015年11月,API Gateway团队添加了一个新功能,以简化CORS设置。{proxy+}
端点,并将所有请求转发到 Lambda 函数。 - adamkonrad{proxy+}
。 - adamkonrad这里是一个示例,希望这可以对您有所帮助:
...
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
我有一个适用于任何方法的HTTP API网关解决方案。 如果您在任何方法上使用授权器,您的授权器将拒绝OPTIONS请求,因为它不包含Authorization/Bearer令牌。 解决方案很简单: 在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)
}
这对我有效。