Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS error on localhost, Is that a normal?

I am running a node.js API on port 8000 which is connected locally to mongo db.

I then start my react server on port 3000 and straight away in console I get the error:

Access to XMLHttpRequest at 'http://localhost:8000/api/hero/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Is this normal for a localhost setup?

like image 334
user10980228 Avatar asked Jun 27 '19 14:06

user10980228


3 Answers

Yes, because CORS doesn't care about localhost in any specific way. Instead, the combination (!) of hostname and port is being used to differ between multiple parties.

Hence, for CORS, localhost:3000 is something completely different than localhost:8000, so, yes, this is normal.

like image 198
Golo Roden Avatar answered Oct 18 '22 19:10

Golo Roden


I guess localhost:3000 is running webpack dev server? If so the simplest way to resolve this is to config your webpack dev server to proxy the request for you, so no need to add CORS handling on your own express server

in your webpack.conf.js, add

devServer: {
  proxy: {
    '/api': 'http://localhost:8000'
  }
}
like image 34
Yongzhi Avatar answered Oct 18 '22 19:10

Yongzhi


Access-Control-Allow-Origin block all request, that are not defined in your node.js API

Add the following lines to your node.js server. This allows you to access the api from every url.

    this.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, authorization");
        res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
        next();
    });
like image 1
Janneck Lange Avatar answered Oct 18 '22 21:10

Janneck Lange