I am trying to set up a very basic API that returns a selected state from a drop down box from the front end. I want to send the state in the request body, and then return the state back in the response to make sure I can get it into my lambda function.
I am trying to make a post request from my frontend to my backend and I keep getting the following exception:
Access to fetch at '(my-endpoint)' from origin 'http://127.0.0.1:5500' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Here is my code when making the API call:
fetch(url, {
method: "POST",
body: JSON.stringify({
state: "Colorado"
}),
headers: {
"Content-type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*",
},
})
Here is my deployed API Gateway CORS configuration:
CORS Config Image
Here are my API Gateway Trigger details:
API type: HTTP
Authorization: NONE
CORS: Yes
Detailed metrics enabled: No
Method: ANY
And finally, my python code in my lambda function:
import json
def lambda_handler(event, context):
request_body = json.loads(event['body'])
state = request_body['state']
return {
'statusCode': 200,
'headers': {
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*'
},
'body': json.dumps(state)
}
I am confused as to why it is not picking up my CORS configuration on the resource side?
I tried to send the request using the js fetch method, and I see the error in the console upon sending the request. I have configured CORS on the backend so I am stuck with why it it’s allowing the request to go through. I am testing with my frontend hosted locally, and my API hosted on AWS. It works in postman, but I aware that postman works without needing a valid CORS configuration.