Enabling CORS for ExpressJS APIs

Views: 187   

In the world of serverless & SPAs we can't expect the webapp and the supporting APIs to run under the same domain origin. In those situations, we have to enable CORS to make browsers work without CORS blocking issues.

You can eighter enable the CORS with custom code or can use some of the popular libraries like cors ( https://www.npmjs.com/package/cors ). In this post, I'll be showing how to use the NPM cors library and enabling the CORS on API endpoints.

Enabling for all the API endpoints


var express = require('express');
var app = express();

var cors = require('cors');


app.use(cors()); // This enabled CORS for all API endpoints in the express app



app.listen(5000, () => console.log('App started @ 5000'));

Enabling for particular endpoint

var express = require('express');
var app = express();

var cors = require('cors');

// cors enabled endpoint
app.get('/api/ping', cors(), (req, res) => {
    res.send('pong');
});

// without cors
app.get('/hi', (req, res) => {
    res.send('hello');
});

This way you can control the APIs where you want to enable CORS.

On By