使用CORS仍会产生跨原点错误 [英] Using CORS Still Give Cross Origin Error

查看:61
本文介绍了使用CORS仍会产生跨原点错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用$ http 访问节点路由rel = nofollow> cors 模块。我尝试了一个简单的

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

app.use(cors());

,但仍然会收到错误。而且我尝试从 cors文档中添加URL白名单

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

但是我仍然遇到错误

XMLHttpRequest无法加载localhost:8888 / someroute / undefined。跨源请求仅支持以下协议方案:http,数据,chrome,chrome-extension,https,chrome-extension-resource。

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.

我认为使用cors模块可以避免此问题。我该怎么解决?

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

推荐答案

这里的问题是您的客户需要向URL请求

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

浏览器将其解释为对主机 8888 使用方案 localhost 。但是, localhost 并不是Chrome支持CORS的方案;只有 http https data 之类的东西。

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/...")

但它需要一个领先的方案,例如 http:// https://

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

请注意,如果尝试使用文件 about 方案请求资源,也会收到类似的错误。

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

这篇关于使用CORS仍会产生跨原点错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆