CORS + Cordova:问题:Access-Control-Allow-Origin

Nav*_*vet 18 javascript ajax jquery cors cordova

我一直在搜索这个问题,但我仍然找不到任何解决方法.

我正在开发一个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("...");
    }
});
Run Code Online (Sandbox Code Playgroud)

我一次又一次地得到同样的错误:

XMLHttpRequest无法加载https://google.com/.请求的资源上不存在"Access-Control-Allow-Origin"标头.因此不允许原点'null'访问

原点'null'是因为我从以下代码运行代码:file:///D:/Projets/LoL/www/index.html并且我读到导航器正在阻塞,但如果我禁用安全性它也不能正常工作--disable-web-security 当然,我无法访问服务器我想加入.

非常感谢你的帮助 !

Nie*_*eek 19

您需要Cordova白名单插件:https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-whitelist/.

在config.xml中有这个:

<access origin="*" />
<allow-navigation href="*"/>
Run Code Online (Sandbox Code Playgroud)

并在index.html中使用Content-Security-Policy元.就像是:

<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data:">
Run Code Online (Sandbox Code Playgroud)

  • 当我作为浏览器运行时,它对我不起作用.我还有:"跨来源请求阻止:同源策略不允许在http读取远程资源://本地主机:7788/testAction这可以通过将资源移动到同一个域或启用CORS是固定的. (6认同)
  • 将 &lt;allow-navigation href="*"/&gt; 添加到 config.xml 为我解决了这个问题。将元标记添加到index.html 给我带来了一些奇怪的错误 (2认同)