Javascript AWS APIGateway CORS for Lambda代理不适用
我已经使用Javascript AWS APIGateway CORS for Lambda代理不适用,javascript,amazon-web-services,aws-lambda,aws-api-gateway,Javascript,Amazon Web Services,Aws Lambda,Aws Api Gateway,我已经使用POSTLambda代理方法和用于CORS头的OPTIONS方法设置了APIGateway资源 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
POST
Lambda代理方法和用于CORS头的OPTIONS
方法设置了APIGateway资源
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方法设置进行其他更改?似乎需要在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)
})
请检查以下几点
- 访问控制允许标头
- 访问控制允许方法
- 访问控制允许源
Daniel更好的方法是使用API网关,使用CORS相关的头来丰富lambda的有效负载,如下所述:
这是一种更具可扩展性且不易出错的方法。您不能期望CORS与“localhost”一起工作,可能是因为这是假的,而且您的浏览器知道这一点。使用
http://lvh.me
或http://www.127.0.0.1.xip.io
。这些是localhost的别名,但您的浏览器不知道。@asdfasdfads您是否也在网关中设置了选项标题响应?这肯定对我有用,考虑到对这个答案的投票,它肯定对其他人也有用。对我有用谢谢。我快发疯了!我正在使用api网关触发代理lambda。我只在lambda响应中添加了“Access Control Allow Origin”:“*”头,它成功了!将API GW代理与Lambda集成。我很难让CORS工作。因此,我的解决方案是从后端发送CORS头,并删除Cloudformation模板中的“选项”和“CORS”。之后它终于开始工作了。当API处于代理模式时,此方法将不起作用。