Using CORS Still Give Cross Origin Error

邮差的信 提交于 2019-12-24 16:27:11

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/34294494/using-cors-still-give-cross-origin-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!