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.

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());