CORS + Cordova:问题:Access-Control-Allow-Origin
我一直在搜索这个问题,但我仍然无法找到任何解决方案。
我正在开发一个App cordova(basicely HTML / JS)所以:该应用程序在导航器上运行,我无法向API发出ajax请求: https : //developer.riotgames.com/但是我要说我只想获得谷歌页面。
我怎么做到这一点,这甚至可能吗? 这是一个简单的例子:
$.ajax({ type: "GET", url: "https://google.com", dataType: "text", success: function(response){ alert("!!!"); }, error: function(error){ alert("..."); } });
我一次又一次地得到同样的错误:
XMLHttpRequest无法加载https://google.com/ 。 请求的资源上不存在“Access-Control-Allow-Origin”标头。 因此不允许原点’null’访问
原点’null’是因为我从以下代码运行代码: file:///D:/Projets/LoL/www/index.html
并且我读到导航器正在阻塞,但是如果我禁用它也不起作用--disable-web-security
当然,我无法访问我想加入的服务器。
非常感谢你的帮助 !
您需要Cordova白名单插件: https : //cordova.apache.org/docs/en/latest/reference/cordova-plugin-whitelist/ 。
在config.xml中有这个:
并在index.html中使用Content-Security-Policy元。 就像是:
我在nodjs服务器中添加了以下内容来解决我的问题;
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"); next();
});
如果您使用nodejs,这可能会有所帮助。
谢谢