I have an HTTPApi API Gateway created with the Serverless Framework. But for some routes, the CORS is not working.
provider:
name: aws
runtime: nodejs12.x
stage: dev
region: us-west-2
timeout: 29
httpApi:
cors:
allowedOrigins:
- '*'
allowedMethods:
- GET
- OPTIONS
- POST
- PUT
- DELETE
allowedHeaders:
- Content-Type
- X-Amz-Date
- Authorization
- X-Api-Key
- X-Amz-Security-Token
- X-Amz-User-Agent
- X-Transaction-Key
- Access-Control-Allow-Origin
I tried setting the cors:true
option on the provider but still doesnt work.
This is the response returned on all routes wether it is 4xx or 2xx codes.
return {
statusCode: StatusCode,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials" : true,
"Access-Control-Allow-Headers" : "*",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET,PUT,DELETE"
},
body: JSON.stringify(Res, null, 2),
};
If I check the console I can see that the options are indeed applied
However, some routes actually work
And some others don't, the ones that don't work have the X-Transaction-Key
header and the OPTIONS
does not return the access-control-allow-headers: authorization,content-type,x-amz-date,x-amz-security-token,x-amz-user-agent,x-api-key,x-transaction-key
header
What am I missing? Thanks in advance
I have faced a similar problem. After 3 days of pulling my hair. I have found my problem. Everything was ok except, In my client, there were few wrong URLs(spelling mistakes) pointing to my server API. This is why few API was ok and few of them not working properly.
After fixing to the right URL everything is ok. Here is my learning, hope someday it will help others:
Check you're serverless.yml file's cors section, here is an example
Check Lamdba for proper response header as question contains
Additional Tools for troubleshooting:
https://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-cors-errors/
https://aws.amazon.com/premiumsupport/knowledge-center/support-case-browser-har-file/
https://toolbox.googleapps.com/apps/har_analyzer/
Hope it will be helpful, Thanks!
Happy Coding