我已经在谷歌搜索了好几天来解决我的问题。但没有什么能解决我的问题。我只想用Cordova最新版本(Cordova Version11.0.0)构建简单的移动应用程序。问题是从外部域获取数据的croos域。
在index.html文件中,我将代码放在下面:
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://app.example.com 'unsafe-eval'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:*;">对于index.html的jquery请求,我将如下所示:
<script src="scripts/jquery.mobile-1.4.5.min.js"></script>
<script src="scripts/jquery-3.6.0.min.js"></script>
<script>
$(document ).bind( "mobileinit", function() {
$.mobile.allowCrossDomainPages = true;
$.support.cors = true;
});
</script>
<script src="scripts/bootstrap.min.js"></script>
<script>
function ambilCoba()
{
var loginString ="view=all";
$.ajax({
type: "GET",
dataType:"json",
crossDomain: true,
cache: false,
url: 'https://app.example.com/test.php',
data: loginString,
success: function(json){
$('#kotbah').html(json['output'][3]);
}
});
}
</script>正如我所读到的,jquerymobile的位置必须是正确的。我试着把它放在许多位置,但仍然没有运气。
在config.xml文件中,我放置了以下内容:
<access origin="*" />
<allow-intent href="https://*/*" />
<allow-intent href="http://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
<allow-navigation href="https://*/*" />
<allow-navigation href="http://*/*" />在我想要获取数据的外部域(test.php),我放置了以下代码:
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Content-Length: 0');
header('Content-Type: text/plain');
header('Content-Type: application/json');
$p=array(1,2,3,4);
return json_encode($p);
?>在科多瓦的index.html,应该打印的结果是4。它在本地浏览器中工作。但当我试图在Android模拟器上运行时,它什么也没有显示出来。试图构建APK文件并将其安装在移动电话上,也没有结果。
我还尝试使用XMLHttpRequest作为建议。守则如下:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200){
var container = document.getElementById('kotbah');
container.innerHTML = xhr.responseText;
}
else
{
alert(this.status);
alert(this.statusText);
alert(this.responseText);
}
}
xhr.open('GET', 'https://app.example.com/APP/test.php', true);
xhr.send(null);我设置了状态警报,以查看Android中到底发生了什么。在Android仿真程序中,状态警报为404,即未找到页面。但是URL是真正存在的。
我试了好几天了,但还是没有运气。2年前,我使用cordova,但版本不同,上面的配置没有问题。我还读到我需要使用whitelisting-plugin.我试过这样做,但是在github,它说在Cordova版本6和更高版本中不再需要白名单插件。
在从外部域获取PHP数据的所有代码中,我遗漏了什么?请帮帮忙。谢谢。
发布于 2022-04-08 12:14:59
你有两个选择。或者使用主机方案设置与API相同的域。
<preference name="scheme" value="app"/>
<preference name="hostname" value="localhost"/>或者通过使用Android来绕过安全性
<preference name="AndroidInsecureFileModeEnabled" value="true" />对于iOS
<plugin name="@globules-io/cordova-plugin-ios-xhr">
<preference name="InterceptRemoteRequests" value="all" />https://stackoverflow.com/questions/71791084
复制相似问题