How to enable cors nodejs with express?

Solution 1:

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());

Solution 2:

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.