Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

amazon web services - How to Enable CORS for an AWS API Gateway Resource

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.

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:

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

(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) and add the Access-Control-Allow-Origin as a 200 response header in your Method Response config.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...