Skip to content

How to enable CORS programmatically on serverless express? #384

Open
@mjza

Description

@mjza

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?

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions