Reputation: 85
I want to send an email through lambda function on AWS. I also used API gateway. I enable cors there and send headers with lambda function and in react app too.
Lambda Function
var response = {
statusCode: 200,
headers: {
'Access-Control-Expose-Headers': 'Access-Control-Allow-Origin',
'Access-Control-Allow-Credentials': true,
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
}
};
My React APP
const awsEndpoint = 'myawsendpoint.amazonaws.com'
axios.post(awsEndpoint, {
headers: {
'Access-Control-Expose-Headers': 'Access-Control-Allow-Origin',
'Access-Control-Allow-Credentials': true,
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
formEmail,
formSubject,
formMessage
})
In the console Im getting below error chrome-console-error
Upvotes: 2
Views: 7714
Reputation: 61
Adding "Access-Control-Allow-Origin" header in the method response of your post method should be enough
Upvotes: 0
Reputation: 1
Have you tried to set a proxy in your package.json? This will allow you to access your AWS gateway from localhost.
in your package.json
...
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "myawsendpoint.amazonaws.com",
....
then you can use a partial path to access your resource
fetch("/your-resource", options)
Upvotes: 0
Reputation: 320
I ended up creating a small lambda function and integrating it to an OPTIONS method at the "/{proxy+}" path. Instructions below, best of luck!
I used the python hello-world template and dropped this in:
import json
def lambda_handler(event, context):
return {
'statusCode': 200,
'headers': {
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS,POST,GET'
},
'body': json.dumps('Hello from Lambda!')
}
That got me up and running. I figure you can tighten down the restrictions once you know it's working. Below is a screenshot of my CORS settings when I initially got mine working as well:
Hope that's helpful!
Upvotes: 0
Reputation: 41
to solve this issue you need to update your CORS policy (for each route, GET, DELETE, OPTIONS, etc) in the AWS API Gateway console. I would read this great Medium article that has screenshots and a detailed explanation of cors
Solution: https://codeburst.io/react-js-api-calls-to-aws-lambda-api-gateway-and-dealing-with-cors-89fb897eb04d
Upvotes: 2