CodeGenieApp / CodeGenieApp/serverless-express

How to enable CORS programmatically on serverless express?

Open
#384 1 comment 0 reactions 1 assignee Claimed by @brett-vendia View on GitHub
question
Dominant language
JavaScript
Stars
5.3k
Forks
676
PR merge metrics
No merged PRs in 30d

Description

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:

```js
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](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html) if I want to activate the CORS I have to apply this changes:

```js
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`:

```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`?**

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.