Serverless-express: Getting a CORS error in the response.

Created on 19 Apr 2018  路  4Comments  路  Source: vendia/serverless-express

I'm trying to use this module to build a serverless app and stuck at a point where I can't seem to get the response to have CORS header for a GET request.

I tried adding the header manually but doesn't work. Adding the Lambda handler code below.

exports.handler = (event, context) => {

if (event.headers) {
event.headers["Access-Control-Allow-Origin"] = "*";
event.headers["Access-Control-Expose-Headers"] = "Origin";
}

awsServerlessExpress.proxy(server, event, context);
};

In the express app, I have added below,

app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With," +
" Content-Type, Accept");
next();
});

Also, I'm using serverless for deploying the app and have enabled cors in the serverless.yml config file.

Does anyone know of a solution to this problem?

Most helpful comment

Nothing obviously wrong with that. Have you tried using the Express cors middleware instead?

All 4 comments

You need to configure on API Gateway enabling CORS. This code just works on Lambda.

Nothing obviously wrong with that. Have you tried using the Express cors middleware instead?

Thanks! It works with the cors middleware. Wondering why it wouldn't work with the above.

Not sure but I'm glad it's working now!

Was this page helpful?
0 / 5 - 0 ratings