I\'m stuck on an issue with API gateway and I\'ve gone through all the other SO answers on this, AWS forums and have been through their docs but still no joy.
I am t
If this is still not working for you, be sure to JSON.stringify() your json object if you are using $.ajax. If not, you will still be returned an error that claims to be a CORS-related error. But if you send the same json object using Postman, the request will succeed. Try it out...
Digitalkapitaen's answer is correct; here is the code to save someone the trouble of looking up how to set an HTTP response header in Lambda:
exports.handler = function(event, context, callback) {
callback(null, {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*"
}
});
};
For someone looking to integrate @Digitalkapitaen's solution in Flask, here's the code below:
app = Flask(__name__)
cors = CORS(app, resources={r"/*": {"origins": "*"}})
@app.route("/")
def helloWorld():
return "Hello, cross-origin-world!"
Do install the flask-cors module by doing a:
pip install -U flask-cors
The response for the GET request to the Lambda function must also contain the Access-Control-Allow-Origin
header.
In case you want to change only one header instead of replacing all headers as is shown in Words Like Jared answer. You can use this code:
'use strict';
module.exports.handler = (event, context, callback) => {
const response = event.Records[0].cf.response;
const headers = response.headers;
headers['access-control-allow-origin'] = [{ key: 'Access-Control-Allow-Origin', value: "*" }];
return callback(null, response);
};
Another examples can be found on Adding HTTP Security Headers Using Lambda@Edge and Amazon CloudFront. It works same for normal Lambda function.