NodeJS : Solving Cross Origin(CROS) Request Block with Code

In NodeJS we try to access the request from unknown URL(for example localhost) it blocks our request and return CROS error on browser. This type of errors are normally arise from Chrome browsers.

To resolve this blocking we need to inform our express app to allow headers with specified access methods. Normal allowing methods are “PUT, GET, POST, DELETE, OPTIONS”.

Sample Code:

var express = require('express');
var app = express();
// Allow CROS
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");