XmlHttpRequest仅使用cordova android获取状态0

时间:2017-05-18 10:36:54

标签: javascript android cordova xmlhttprequest

我正在开展一个cordova项目,并且我试图连接到一个安静的api,但它一直在回复一个空白的回复。 我假设这是一个与科尔有关的问题,但我无法弄清楚我错过了什么,没有一个旧的相同问题帮助了我 当我在浏览器上运行应用程序时它工作正常,我得到了

Status Code: 200
Pragma: no-cache
Date: Thu, 18 May 2017 17:50:41 +0000
Host: localhost:8001
X-Powered-By: PHP/7.1.0RC6
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Content-Type: application/json;charset=utf-8
Access-Control-Allow-Origin: *
Cache-Control: no-store, no-cache, must-revalidate
Connection: close
Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept, 
Origin, Authorization
Expires: Thu, 19 Nov 1981 08:52:00 GMT

但是当我在Android设备上运行它时,我的状态为0 我使用的是cordova 6.5.0和Android 5.1 我试图删除白名单插件并重新安装它,我将这些行添加到我的config.xml

<access origin="*" />
<allow-navigation href="*" />
<allow-intent href="http://*/*" />

和CSP到我的index.html文件

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 
'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval' *">

我使用此代码来调用api:

function testAPI(){
    var ajax = new XMLHttpRequest();
    ajax.open("GET","http://localhost:8001/layer/hospitals",true);
    ajax.onreadystatechange=function(){
      if(ajax.readyState == 4) {
         if (ajax.status == 200 || ajax.status == 0) {
             alert(ajax.responseText);
         }
      }
    }
    ajax.send();
}

有没有人知道我错过了什么?

1 个答案:

答案 0 :(得分:2)

由于 localhost 在移动设备中不存在,您需要将 localhost 替换为您的IP地址,如下所示

ajax.open("GET","http://your ip address:8001/layer/hospitals",true);

希望对你有帮助