Home > database >  How to get CORS working with Serverless and httpApi
How to get CORS working with Serverless and httpApi

Time:08-16

I'm having a problem with my serverless setup. I am new to httpAPI, just migratinging from http. I'd like to get it working but can not sort out CORS. Postman returns the response just as I expect but chrome is throwing a CORS error. Any help on what I've got wrong would be great. my serverless.yml looks like

service: serverless
frameworkVersion: '3'

provider:
  name: aws
  runtime: nodejs16.x
  httpApi:
    cors: true
    authorizers:
      customAuthorizer:
        type: request
        functionName: authorizerFunc

functions:
  user:
    handler: src/users/index.handler
    events:
      - httpApi:
          path: /user
          method: any
          authorizer: 
            name: customAuthorizer
  authorizerFunc:
    handler: src/authorizer/index.handler

the handler for src/users/index.handler is:

module.exports.handler = async (event, context, callback) => {
    callback(null,{
        statsCode: 200,
        body:{message:'Success'}
    });
}

This works fine in thunder client/postman but i get cors issues in the web browser. What am I missing here?

Edit: Mihail Feraru's reply below was helpful once I resolved the root issue. Turn's out I had issues with my preflight check. My custom authorizer was rejecting any preflight check, thus requests via chrome were failing.

CodePudding user response:

Adding cors: true to your configuration only handles preflight requests. If you want your endpoint to be compliant with CORS's requirements you need to also return the correct headers in your function:

module.exports.handler = async (event, context, callback) => {
    callback(null,{
        statsCode: 200,
        headers: {
           'Access-Control-Allow-Origin': '*',
        },
        body: { message: 'Success' }
    });
}

Note: It's not a good practice to use * as your allowed origin in production. I recommend you to read a guide about CORS, something like this for example. Check also this guide about using CORS and serverless framework together.

  • Related