HTTPApi + Serverless Framework + API Gateway CORS not working

6.2k Views Asked by At

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

3

There are 3 best solutions below

2
On

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:

  1. Check you're serverless.yml file's cors section, here is an example

     cors:
        origin: '*'
        headers:
          - Content-Type
          - X-Amz-Date
          - Authorization
          - X-Api-Key
          - X-Amz-Security-Token
        allowCredentials: false
    
  2. Check Lamdba for proper response header as question contains

Additional Tools for troubleshooting:

Hope it will be helpful, Thanks!

Happy Coding

0
On

Have you tried fixing the 'cors: true' value in the function event as in Serverless with cors ?

0
On

I faced the same problem. Please check whether you are sending all the correct Headers. If any additional header you send and don't fine tune the cors config you will get a CORS error

For me I had a typo with Authorization header. Took me 3+ days to figure it out lol!

Please check this link for detailed documentation and how to fine tune cors for httpAPi https://www.serverless.com/framework/docs/providers/aws/events/http-api