Reputation: 6800
I am send post request from my web-page to AWS API Gateway which is invoking a lambda function. CORS is enabled in the API Gateway.
Error:
Failed to load api_gatewau_url: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'url' is therefore not allowed access.
The resource is having two methods:
How to solve CORS issue?
Below is the code for sending post request.
$.ajax({
type: "POST",
crossDomain: true,
url: "api_gateway_url",
data: JSON.stringify({
"param1": value1,
"param2": value2
}),
I have also tried to add headers with allow origin true etc but no luck.
Strangest thing, same configuration and request I am trying with different api gateway then it is working fine without any errors.
Upvotes: 5
Views: 10793
Reputation: 75
If you're using lambda proxy you have to add the Access-Control-Allow-Origin header in your lambda
"Access-Control-Allow-Origin": "*"
If not using lambda proxy you can go to API Gateway click on the actions drop down and select enable CORS to enable it.
Upvotes: 1
Reputation: 5426
If you are using proxy integration in API Gateway, then enabling CORS from API Gateway doesn't work. You have to set the Header 'Access-Control-Allow-Origin' from your Lambda code itself.
Its mentioned in the doc.
Python code sample:
response = {
'statusCode': 200,
'headers': {
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps({'message': 'CORS enabled')
}
return response
Upvotes: 6
Reputation: 13055
Based on your type of integration you need to return the COR's headers.
More detail can be found at,
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#The_HTTP_response_headers
If you are using ANY integration, you can return the headers from your Lambda or other sources where you are integrating with.
For Lambda,
module.exports.hello = function(event, context, callback) {
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin" : "https://domain:port", // Required for CORS support to work
"Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
},
body: JSON.stringify({ "message": "Hello World!" })
};
callback(null, response);
};
If you are using S3,
https://docs.aws.amazon.com/AmazonS3/latest/user-guide/add-cors-configuration.html
API Gateway CORS Mapping:
https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html
Hope it helps.
Upvotes: 1