我有一个非常简单的 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 页面(从 file://)时,我得到 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 应用程序运行时,我得到 {"readyState":4, "responseText":"<!DOCTYPE HTML PUBLIC \" -//IETF//DTD HTML 2.0//EN\">... blah blah ... 403 Forbidden ... , "status":403, "statusText": "Forbidden"}
.
发生什么事了? 如何通过手机应用程序执行此请求?
最佳答案
当我在我的服务器上禁用 ModSecurity 后,此问题得到解决。
对我来说,我可以通过 cPanel 访问我的主机来做到这一点:
cPanel > 安全 > ModSecurity
我希望这对其他人有帮助。
感谢 @jcesarmobile 指出问题必须出在服务器上。
关于javascript - 403 禁止从 Cordova 5.0.0 应用程序执行 AJAX POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30319572/