【问题标题】:Ajax requests are failing on Cordova Android appCordova Android 应用程序上的 Ajax 请求失败
【发布时间】:2022-08-19 02:07:48
【问题描述】:

当我在 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:;\">

    标签: javascript android html cordova cordova-plugins


    【解决方案1】:

    根据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://),它不强制执行 COR。这就是为什么您看到 XHR 请求在 9.x 中有效,但在 10.x 中无效。您可以通过启用 AndroidInsecureFileModeEnabled 使 10.x 表现得像 9.x

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-19
      • 1970-01-01
      • 2013-08-09
      • 2017-06-11
      • 1970-01-01
      • 2015-08-07
      相关资源
      最近更新 更多