3

I created a REST Api using nodejs and mongodb and i wanted to test it in postman but while doing so I am getting a CORS error.

var express = require('express');
var log = require('morgan')('dev');
var bodyParser = require('body-parser');

var properties = require('./config/properties');
var db = require('./config/database.js');
//hero routes
var herosRoutes = require('./api/heros/heros.routes');
var app = express();

//configure bodyparser
var bodyParserJSON = bodyParser.json();
var bodyParserURLEncoded = bodyParser.urlencoded({extended:true});

//initialise express router
var router = express.Router();

// call the database connectivity function
db.mongoc();

// configure app.use()
app.use(log);
app.use(bodyParserJSON);
app.use(bodyParserURLEncoded);

// Error handling
app.use(function(req, res, next) {
    res.setHeader("Access-Control-Allow-Origin", "*");
     res.setHeader("Access-Control-Allow-Credentials", "true");
     res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
     res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers,Authorization");
   next();
 });

// use express router
app.use('/api',router);
//call heros routing
herosRoutes.hero(router);

// intialise server
app.listen(properties.PORT, (req, res) => {
    console.log(`Server is running on ${properties.PORT} port.`);
})

Whenever i make any create or get request, i get this CORS error in postman. How to solve this?

CORS Error: The request has been blocked because of the CORS policy

Himanshu Ranjan
  • 282
  • 1
  • 7
  • 22
  • Does this answer your question? [Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?](https://stackoverflow.com/questions/7067966/why-doesnt-adding-cors-headers-to-an-options-route-allow-browsers-to-access-my) – Henke Jan 21 '21 at 11:28

2 Answers2

4

Have you tried the CORS package from Express? It's a simple setup:

npm i cors

Then just use it in your app (this enables ALL CORS requests):

app.use(cors());

Docs

Also answered here.

Ryan
  • 364
  • 2
  • 7
  • its a socket hangup error now, its taking a long time to get the response. – Himanshu Ranjan Aug 29 '20 at 09:26
  • @HimanshuRanjan, Did you remove your previous app.use() for CORS under `// Error handling`? – Ryan Aug 29 '20 at 09:38
  • @HimanshuRanjan, your router config is also strange. What does your herosRoutes file look like? – Ryan Aug 29 '20 at 09:50
  • i did delete it but its still not responding. – Himanshu Ranjan Aug 29 '20 at 16:59
  • https://github.com/Himanshuranjan30/RESTapi_nodejs Can you check the issue in my git please? its not that much of code @Ryan – Himanshu Ranjan Aug 29 '20 at 17:04
  • @HimanshuRanjan, Does this repo reflect the latest version of your app? There are empty files, including your "models", which are being imported in other modules, so it's impossible for me to trace through your (rather bizzare) routing. You should get your routes up and functional, then move on to the CORS question. – Ryan Aug 29 '20 at 18:40
  • Solved! Thank you. – Himanshu Ranjan Aug 30 '20 at 08:07
4

if someone is still having this issue, Postman doesn't provide an origin when calling the API, so when we have restricted CORS policy an error is generated saying Error: Not allowed by CORS.

Sample code for bypassing this issue is this:

const whitelist = ['https://localhost:3001']
const corsOptions = {
 origin: function (origin, callback) {
    if(!origin){//for bypassing postman req with  no origin
      return callback(null, true);
    }
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}
app.use(cors(corsOptions));