Dinesh Ahuja
Dinesh Ahuja

Reputation: 1015

No 'Access-Control-Allow-Origin' header is present on the requested resource in NodeJS

I am using a NodeJS app running on,

http://localhost:3000

I have one more NodeJS API running on http://localhost:3002 .

I am receiving the following error when I am calling the API in the app.

Failed to load http://localhost:3002: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

I have added CORS in the server.js file of http://localhost:3002

var cors = require('cors');

app.options('*', cors()); 

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");
    next();   
});

// define a simple route
app.get('/', (req, res) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 
    res.json({"message": "Welcome to Application"});
});

app.listen(3002, () => {
    console.log("Server is listening on port 3002");
});

I am still receiving the error. Whenever I am opening the URL http://localhost:3000 , I can see the error in the chrome developer console.

Upvotes: 0

Views: 802

Answers (2)

Abdullah Khan
Abdullah Khan

Reputation: 645

well first try

npm install cors
app.use(cors())

if it doen't work then try this

allowCrossDomain = function(req, res, next) {
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
  if ('OPTIONS' === req.method) {
    res.sendStatus(200);
  } else {
    next();
  }
};

app.use(allowCrossDomain);

Upvotes: 0

user10504705
user10504705

Reputation: 33

You should use the cors like this

app.use(cors()); 

Reference

Simple Usage (Enable All CORS Requests)

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')
})

Upvotes: 2

Related Questions