javascript - XmlHttpRequest 仅在 Cordova Android 中获取状态 0

标签 javascript android cordova xmlhttprequest

我正在开发一个cordova项目,我正在尝试连接到一个restful api,但它不断返回空白响应。 我假设这是一个与 cors 相关的问题,但我不知道我错过了什么,而且旧的相同问题都没有帮助我 当我在浏览器上运行该应用程序时,它工作正常,我得到

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

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

最佳答案

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

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

希望对你有帮助

关于javascript - XmlHttpRequest 仅在 Cordova Android 中获取状态 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44045427/

相关文章:

Javascript:为什么在 console.log 中调用变量时将 "()"放在变量后面?

javascript - 相等运算符为什么 === 会导致未定义的异常,而 == 按预期工作?

java - RSS 应用程序,我的 ListView 出现问题

android phonegap 应用程序在加载太多 javascript 时失败

android - 与 Ionic 2 中的 SharedPreferences 等效的类是什么?

javascript - Bootstrap - 调整窗口大小时 react 和适合的缩略图

javascript - 模计算中的奇怪结果

javascript - 无法在 Android 设备的后退按钮上退出 phonegap 应用程序

android - 接收广播错误

Android Studio 找不到 Boost header