CORS not working

serverless.yml

card:
  handler: src/get-card.handler
  events:
  - http:
      path: card
      method: post
      cors:
        origin: "*"
        headers:
          - Content-Type
          - X-Requested-With
          - X-Amz-Date
          - Authorization
          - X-Api-Key
          - X-Amz-Security-Token
          - X-Amz-User-Agent

src/get-card.js

const handler = (event, context, callback) => {
  let paypload = {
    card: "xxxx"
  }
  
  const response = {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
    },
    body: JSON.stringify(payload),
  }

  callback(null, response)
}

Error:
Access to XMLHttpRequest at ‘https://xxx.execute-api.us-east-1.amazonaws.com/dev/card’ from origin ‘https://yyy.com’ has been blocked by CROS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Anyone can help me to fix this issue? Thank you.

1 Like

Not sure if this is exactly what you’re looking for, but I noticed that sometimes I was getting CORS error responses when something else inside my lambda execution was failing (check your cloudwatch logs). Specifically my lambda function didn’t have permission to write to my DynamoDB table, for some reason API gateway returns the issue as a CORS problem. If this is unrelated, trying using middy: https://github.com/middyjs/middy

eg

const someHandler = middy((event, context, callback) => {
      myFn()
        .then((result) => {
          const res = { body: JSON.stringify(result) };
          callback(null, res);
        })
        .catch(callback);
    }).use(cors());
1 Like

i agree with Craig, i’m finding this to be the case for errors that happen within the function or if i try the wrong HTTP method i.e. PUT when it should be a POST. idk if this is a SLS bug or it just means I’m constructing my responses incorrectly on errors

Cors should work by default. You likely do not need all those headers for both request and response. I suggest you try one of those http api example for aws and nodejs first.