I am trying to access a DynamoDB from a react app using Api Gateways and Lambda functions.
I made de API and tested the post method in https://apitester.com/, it works fine. I send a payload like {"command": "getall"}
and get this response: {"statusCode": 200, "body": "\"Hello from Lambda!\""}
But when I call the API from the react app I get this error:
Access to XMLHttpRequest at
'https://9xovixi3ua.execute-api.us-east-2.amazonaws.com/default/bmsa-calc-admin'
from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested
resource.
My code looks like this:
async function getUser() {
axios.post('https://9xovixi3ua.execute-api.us-east-2.amazonaws.com/default/bmsa-calc-admin',
{
command: 'getall'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
From the API Gateway console I added an OPTIONS method, and then the method response header Access-Control-Allow-Origin
Thanks in advance!
So, I did a couple of things to get this to work. I added the response headers with the corresponding mapping values like this guy does. You can see that in the picture from the question.
Then, as in my case the API triggers a Lambda function, I added this to the return value of the function (python):
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, PUT, GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With'
}
So, the complete return looks like this:
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!'),
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, PUT, GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With'
}
}
This is working fine, though I'm not sure I understand what is really happening, so if anyone wishes to explain more in the comments, it would be great.