如何为AWS API网关资源启用CORS

问题描述:

我使用AWS API Gateway& AWS Lambda,当我配置CORS时,我遇到了这样的问题-我能够为OPTIONS方法配置CORS响应标头,但没有为GET方法配置.

I created REST API using AWS API Gateway & AWS Lambda and when I configured CORS I faced with such issue - I was able to configure CORS response headers for OPTIONS method, but didn't for GET method.

我根据 Amazon文档,但是当我调用GET方法时,我没有看到所需的标头(Access-Control-Allow-Methods,Access-Control-Allow-Headers,Access-Control-Allow-Origin).因此,我在客户端出现了错误:

I made it according Amazon documentation, but when I called GET method I didn't see required headers (Access-Control-Allow-Methods, Access-Control-Allow-Headers, Access-Control-Allow-Origin) in response. Due to that I got errors on client side:

无法加载#my_test_rest#:请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许访问来源#my_test_rest_url#.

Failed to load #my_test_rest#: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin #my_test_rest_url# is therefore not allowed access.

作为一个临时解决方案,我用Lambda函数的代码对所需的标头进行了硬编码,但它看起来似乎不是正确的解决方案,我想了解为什么它对我不起作用.有什么想法我做错了吗?

As a temporary fix I hardcode required headers in code of Lambda function, but it looks not like right solution and I'd like to understand why it don't work for me. Any ideas what's I'd doing wrong?

由于您在方法中使用Lambda代理集成,因此您需要:

Since you're using Lambda Proxy integration for your method, you'll need to:

(1)提供Access-Control-Allow-Origin标头作为Lambda响应的一部分.例如:

(1) provide the Access-Control-Allow-Origin header as part of the Lambda response. For example:

callback(null, {
    statusCode: 200,
    headers: {"Content-Type": "application/json", "Access-Control-Allow-Origin": "*"},
    body: JSON.stringify({message: "Success"})
});

(2),并将Access-Control-Allow-Origin作为200响应标头添加到方法响应配置中.

(2) and add the Access-Control-Allow-Origin as a 200 response header in your Method Response config.