serverless-express icon indicating copy to clipboard operation
serverless-express copied to clipboard

How to enable CORS programmatically on serverless express?

Open mjza opened this issue 4 years ago • 1 comments

I hope it is the right repository for asking this question.

I have a aws amplify project and defined a REST API index.js like this:

const awsServerlessExpress = require('aws-serverless-express');
const app = require('./app');

const server = awsServerlessExpress.createServer(app);

exports.handler = (event, context) => {
  console.log(`EVENT: ${JSON.stringify(event)}`);
  return awsServerlessExpress.proxy(server, event, context, 'PROMISE').promise;
};

Based on this documentation if I want to activate the CORS I have to apply this changes:

exports.handler = async (event) => {
    const response = {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "https://www.example.com",
            "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
        },
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

However, in the newest version of AWS cli it generates the expirts.handler like the first snippet of code by using serverless express; and it places the following code in app.js:

// Enable CORS for all methods
server.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "*");
  res.header("Access-Control-Allow-Methods", "OPTIONS,POST,GET");
  res.header("Access-Control-Allow-Credentials", true);
  next();
});

Unfortunately this code does not activate the CORS on my API.

My question is, how can I add headers to aws-serverless-express?

mjza avatar Mar 10 '21 07:03 mjza

Check out the example https://github.com/vendia/serverless-express/blob/mainline/examples/basic-starter-api-gateway-v2/src/app.js#L4-L15

brett-vendia avatar Mar 10 '21 07:03 brett-vendia