我已经使用POST
Lambda代理方法设置了一个APIGateway资源,并为CORS标头设置了OPTIONS
方法。
OPTIONS
方法返回以下标题:
$ curl -i -X OPTIONS https://xxxxxxxxx.execute-api.eu-central-1.amazonaws.com/dev/endpoint1
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 0
Connection: keep-alive
Date: Sat, 18 Feb 2017 17:07:17 GMT
x-amzn-RequestId: xxxx
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token
Access-Control-Allow-Methods: POST,OPTIONS
X-Cache: Miss from cloudfront
Via: 1.1 xxxx.cloudfront.net (CloudFront)
X-Amz-Cf-Id: xxxx==
然而,当我使用生成的Javascript SDK调用POST
端点时,Chrome浏览器控制台会显示以下错误:
XMLHttpRequest cannot load https://xxxx.execute-api.eu-central-1.amazonaws.com/dev/endpoint1.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:8080' is therefore not allowed access.
以及Firefox:
Cross-Origin Request Blocked:
The Same Origin Policy disallows reading the remote resource at https://xxxx.execute-api.eu-central-1.amazonaws.com/dev/endpoint1.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
为什么我的CORS标头没有考虑在内?是否需要对POST方法设置进行其他更改?
答案 0 :(得分:9)
似乎需要在lambda函数中手动添加标题。
对于NodeJS,脚本如下所示:
context.succeed({
"statusCode": 200,
"headers": {
"X-Requested-With": '*',
"Access-Control-Allow-Headers": 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,x-requested-with',
"Access-Control-Allow-Origin": '*',
"Access-Control-Allow-Methods": 'POST,GET,OPTIONS'
},
"body": JSON.stringify(response)
})
答案 1 :(得分:2)
一种更好的方法是使用API网关,通过CORS相关标头来丰富来自lambda的有效负载,如下所述:https://kennbrodhagen.net/2015/12/02/how-to-access-http-headers-using-aws-api-gateway-and-lambda/
这是一种更具可扩展性和更少错误的方法。
答案 2 :(得分:0)
请检查以下几点。
谢谢, 丹尼尔