Reputation: 3351
I am trying to set up an AWS lambda function, however when I call the endpoint, I am getting this error message back in the console.
Access to fetch at 'https://*.execute-api.eu-west-1.amazonaws.com/default/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I have set the CORS policy on the AWS Gateway
Here is my request code... I am just trying to print out the body of the response for testing purposes.
const response = await fetch(
'https://**********.execute-api.eu-west-1.amazonaws.com/default/**************',
{
method: 'POST',
body: "{'test': 'test'}",
headers: {
'X-Api-Key': '*****************************',
},
}
);
const text: any = await response.text();
console.log(text);
Weirdly when I look in fiddler, it is sending the OPTIONS and also returning a correct response, which is currently just printing out the different headers passed to the function.
Upvotes: 0
Views: 698
Reputation: 171
If you've lambda proxy integration enabled you'll have to add headers from lambda.
From AWS documentation CORS section
For a Lambda proxy integration or HTTP proxy integration, you can still set up the required OPTIONS response headers in API Gateway. However, your backend is responsible for returning the Access-Control-Allow-Origin and Access-Control-Allow-Headers headers, because a proxy integration doesn't return an integration response.
exports.handler = async (event) => {
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "https://www.example.com",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET"
},
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
you can read more here
Upvotes: 3