Reputation: 41
How do I enable CORS in Serverless?
I keep getting the following error msg while calling my lambda function.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
I've searched everywhere, and I still couldn't figure out how to fix it. Any help would be greatly appreciated!!!
Here is my setup:
My Python handler, tested with serverless invoke local
def main(event, context):
...operations with pandas...
return {
'statusCode': 200,
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': True
},
'body': json.dumps(response),
}
My serverless.yml
functions:
main:
handler: handler.main
events:
- http:
path: dashboard
method: get
authorizer: aws_iam
cors: true
My frontend, a React app. The API call is made with aws-amplify:
try{
const myInit = {
body: JSON.stringify(this.props.session),
headers: {
"Content-Type": "application/json"
}
};
const calculation = await API.get("clearly", "/dashboard", myInit)
console.log(calculation);
} catch(e) {
...
}
Thanks!
Edit:
While I was trying to enable CORS manually in API Gateway, I got this Invalid Response status code specified
error msg.
Capture
Upvotes: 0
Views: 2016
Reputation: 706
Have you created OPTIONS method with the mock integration type to return the response headers like these
Access-Control-Allow-Methods Access-Control-Allow-Headers Access-Control-Allow-Origin
Just reference ( https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html )
Upvotes: 1