禁止在Cordova 5.0.0应用中做AJAX POST

403 Forbidden doing AJAX POST from Cordova 5.0.0 app

本文关键字:AJAX POST 应用 Cordova 禁止      更新时间:2023-09-26

我有一个非常简单的Cordova应用程序,它试图做一个AJAX POST。

请求的URL simple.php如下所示:

<?php
header('Access-Control-Allow-Origin: *');
die ( json_encode ( array('result'=>'ok') ) );
?>

index.html就是这样:

<head>
    <script src="jquery.js"></script>

    <script>
    $(document).ready( function() {
        $.ajax(
        {
            type: 'POST',
            url: 'http://drawonthe.net/simple.php',
            contentType: 'text/plain',
            xhrFields: {
                withCredentials: false
            },
            success: function(res) {
                alert('got this res : ');
                alert(JSON.stringify(res));
            },
            error: function(err) {
                alert('got this fail : ');
                alert(JSON.stringify(err));
            }
         });
    });
    </script>
</head>

<body>
</body>

我的Cordova config.xml文件包括以下内容:

<content src="index.html" />
<access origin="*" />
<allow-intent href="*" />
<allow-navigation href="*" />
<access origin="content:///*" />

我的应用包含cordova-plugin-whitelist插件。

我在index.html中尝试了各种csp,但没有好的结果。如:

   <meta http-equiv="Content-Security-Policy" content="default-src *; script-src * 'unsafe-eval' 'unsafe-inline'; connect-src *; img-src *; style-src * 'unsafe-inline' ; media-src *; ">

当我访问这个HTML页面本地(从文件://)我得到XMLHttpRequest cannot load http://drawonthe.net/simple.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.,它返回{"readyState":0,"status":0,"statusText":"error"}

当我通过在本地服务器上托管访问HTML页面时,它可以毫无怨言地工作。(正确响应:"{'"result'":'"ok'"}")

当我在Android或iOS设备上运行它作为Cordova App时,我得到{"readyState":4, "responseText":"<!DOCTYPE HTML PUBLIC '" -//IETF//DTD HTML 2.0//EN'">... blah blah ... 403 Forbidden ... , "status":403, "statusText": "Forbidden"}

怎么回事?我如何让这个请求在手机应用程序中工作?

当我在服务器上禁用ModSecurity 时,此问题已解决。

对我来说,我可以通过cPanel访问我的主机:

cPanel> Security> ModSecurity

我希望这对别人有帮助。
谢谢你@jcesarmobile指出问题出在服务器上