Member-only story
Setting up CORS in NodeJS.
CORS is Cross Origin Resource Sharing is a browser side HTTP header based mechanism to prevent cross origin attacks. You can refer here for more details.
How to configure CORS in express NodeJS?
Step 1: Install cors module by running below command.
npm install — save cors
Step 2: import or include using require in the file as shown below.
var Express = require(“express”);
var cors = require(“cors”);
var app = Express();
// enabling cors for all the requests
app.use(cors());
app.get(“/”, (req, res) => {
res.send(“Hello world”);
});
That’s it. CORS enabled for the server. But this is like accepting all the hosts for all the requests, it wont help in reality. lets do more specific cors configurations.
Route specific configuration: To configure route specific, instead of using middle-ware function app.use(), use cors in the route itself.
var Express = require(“express”);
var cors = require(“cors”);
var app = Express();
// enabling route specific or single route cors
app.get(“/”, cors(), (req, res) => {
res.send(“Hello world”);
});
Enabling cors for whitelist hosts: Need to specify origin list in a object and pass that object to cors function to enable.
var Express = require(“express”);
var cors = require(“cors”);
var app = Express();
// enabling cors for selected list of hosts or origins
var corsOptions = {
origin…