我正在开发一个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/