CORS error on localhost, Is that a normal?

Viewed 18692

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?

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.

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

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