繁体   English   中英

Ajax 请求在 Cordova Android 应用程序上失败

[英]Ajax requests are failing on Cordova Android app

当我在 Chrome 浏览器上运行项目时,ajax 请求工作正常,但是当我在 Android 上安装应用程序时,请求不再工作。 这是代码:

    var xhr=new XMLHttpRequest()
            xhr.onerror=function(){
           
                var message=alert(txt('Please turn on mobile data or Wi-Fi','Ligue os dados moveis ou Wi-Fi'))
                
            }
            
            xhr.onreadystatechange=function (){
                if (this.status== 200 && this.readyState == 4){ 
                alert("trye")
                  eval(xhr.responseText)
                
                } 
            }
            xhr.open("POST",`http://dpreaction.ml?i=js`)
            xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
            xhr.send()

config.xml 文件

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.teste.teste" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>DP Reaction</name>
    <description>Inrease your things</description>
    <author email="gilluisfrancisco70@gmail.com" href="http://dpreaction.ml">
        DP Reaction
    </author>
    <content src="index.html" />
    <allow-intent href="*" />
    <access origin="*" />
    <allow-naviation href="*" />
</widget>

这是我的标签:

  <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval'  data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">

根据https://github.com/apache/cordova-android/issues/1354

Content-Security-Policy 是一种不同于 CORS(跨域资源共享)的安全机制。

在 cordova-android@10 中,他们实现了一个 WebAssetLoader,它通过 https://localhost 协议代理请求。 WebAssetLoader 就像一个私有的 web 服务器,只有你的应用可以访问。 这样做是因为某些 web 视图功能要求您处于“安全上下文”(例如 HTTPS)中才能启用这些功能。 这样做,它确实启用了 CORS 强制执行。

Cordova android 9.x 使用普通的旧文件系统 (file://),它没有强制执行 CORs。 这就是为什么您看到 XHR 请求在 9.x 中有效,但在 10.x 中无效。 您可以通过启用 AndroidInsecureFileModeEnabled 使 10.x 表现得像 9.x

因此,如果您使用的是 cordova-android@10,只需在 config.xml 中添加以下首选项:

<preference name="AndroidInsecureFileModeEnabled" value="true" />

我有同样的问题,它为我解决了。 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM