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.
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.