1252748
1252748

Reputation: 15372

Using CORS Still Give Cross Origin Error

I'm trying to access a node route through angular $http using the cors module. I've tried a simple

app.use(cors());

but still get the error. And I've tried adding from the cors documentation a whitelist of URLs

var corsOptions = {
  origin: function(origin, callback){
    var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
    callback(null, originIsWhitelisted);
  }
};

app.get('/someroute/:someparam/', cors(corsOptions), function(req, res, next){
  mymodule.getData(req.params.someparam, function(err, data){
      if (err){
        console.log('error with route', err);
      }else{
        res.json({result: data});
      }
  });
});

But I'm still getting the error

XMLHttpRequest cannot load localhost:8888/someroute/undefined. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

I thought that using the cors module was meant to avoid this problem. How can I solve?

Upvotes: 1

Views: 1153

Answers (1)

apsillers
apsillers

Reputation: 115940

The problem here is that your client needs to make a request for the URL

http://localhost:8888/someroute/undefined

Instead, your client is making a request for

localhost:8888/someroute/undefined

which the browser interprets as a request for the host 8888 using the scheme localhost. However, localhost isn't a scheme that Chrome supports for CORS; only things like http, https, data are.

Somewhere, your client-side code does something like

xhr.send("localhost:8888/...")

but it needs a leading scheme, like http:// or https://.

Note that you get a similar error if you try to request a resource with a file or about scheme.

Upvotes: 3

Related Questions