How to enable cors nodejs with express? How to enable cors nodejs with express? express express

How to enable cors nodejs with express?


do

npm install cors --save

and just add these lines in your main file where your request is going.

const cors = require('cors');const express = require('express');const app = express();app.use(cors());app.options('*', cors());


To enable cors you can do this:

var cors = require('cors');app.use(cors());// to change your ports for different cors stuff:app.set('port', process.env.PORT || 3000);app.listen(app.get('port'), function() {   console.log('we are listening on: ',   app.get('port'))});

Remember that cors are middleware, so you will want to have app.use before it so that your incoming requests will go through cors before they hit your routes.

You can change the ports depending on which one you want to use. I am pretty sure you can also replace the || with && to listen on multiple ports and set cors on those.

In raw node, I believe you have to use the writeHead, but I am not sure about the raw node implementation.


Adding CORS(Cross-Origin-Resource-Sharing) to your node, express app is quite easy...

You need to install cors library via npm first, using the command below:

npm install cors -S

and if you need it globally, just add -g flag to it...

Then in your express app, do this:

const express = require('express');const cors = require('cors');const app = express();app.use(cors());

Also these are other examples for cors from their doc:

var express = require('express')var cors = require('cors')var app = express()app.use(cors())app.get('/products/:id', function (req, res, next) {  res.json({msg: 'This is CORS-enabled for all origins!'})})app.listen(80, function () {  console.log('CORS-enabled web server listening on port 80')})

Configuring CORS Asynchronously:

var express = require('express')var cors = require('cors')var app = express()var whitelist = ['http://example1.com', 'http://example2.com']var corsOptionsDelegate = function (req, callback) {  var corsOptions;  if (whitelist.indexOf(req.header('Origin')) !== -1) {    corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response  }else{    corsOptions = { origin: false } // disable CORS for this request  }  callback(null, corsOptions) // callback expects two parameters: error and options}app.get('/products/:id', cors(corsOptionsDelegate), function (req, res, next) {  res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})})app.listen(80, function () {  console.log('CORS-enabled web server listening on port 80')})