ios - Cordova AJAX 请求不工作

标签 ios ajax cordova

我正在使用 Cordova 5.3.1,我似乎完全无法无误地发出任何网络请求。如果我添加

$.ajax( "http://foo.bar.com/getfeed" )
.done(function() {
    alert( "success" );
})
.fail(function(jqXHR, textStatus, errorThrown) {
    alert( errorThrown );
})
.always(function() {
    alert( "complete" );
});

index.js 它失败并警告 Error: SecurityError: DOM Exception 18 在 iOS 和 SecurityError: Failed to execute 'open on 'XMLHttpRequest':拒绝连接到“http://foo.bar.com/getfeed”,因为它违反了文档的内容安全策略。,所以看起来 CORS 被阻止了。

当前 whitelist plugin按照此 SO post 安装时未正确安装还有这个JIRA issue , 基本上它需要 iOS 平台 >=4.0.0-dev。我仍然可以强制它安装旧版本:

cordova plugin add cordova-plugin-whitelist@1.0.0

根据 SO 帖子和 JIRA 问题中的建议。

但是我仍然无法向外部域发出任何 http 请求。我仍然收到相同的“DOM 异常 18”错误。我的 config.xml 文件当前是

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.company.pearstest" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>CORS test</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <plugin name="cordova-plugin-whitelist" version="1" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
</widget>

允许不同来源的标签最近似乎在不同的版本中发生了变化,因此我在这个文件中尝试了各种不同标签的所有可能的组合。

我还检查了 $.support.cors 以确保 jQuery 允许 CORS 并且确实如此(jQuery 正常工作,因为 AJAX 请求正在运行失败回调而不是静默失败)。

我也有元标记

<meta http-equiv="Content-Security-Policy" content="default-src 'self' https:">

index.html 中。我怀疑这不是我的模拟器阻止 http 请求的问题,因为它是 Android 和 iOS 模拟器以及 Android 设备上的问题。

有人知道为什么我仍然有 CORS 问题吗?谢谢。

最佳答案

您是否尝试过将您的 Content-Security-Policy 配置为:

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

注意 default-src 中的 * 和 ; 的使用- 我还在上面的示例中包含了一些其他说明,以允许通用 JS 库工作...这就是我在为 Android 和 iOS 构建的 JQuery/Handlebars Cordova 5 应用程序中使用的。

关于ios - Cordova AJAX 请求不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32743831/

相关文章:

ios - 连续移动对象 - iOS - SpriteKit

ios - 为什么自动更正弹出窗口没有位于我的文本上方?

ios - 拦截来自 UIWebView 的生成的 URL 请求

ios - Alamofire 4 失败 : Error Domain=NSURLErrorDomain Code=-999 "cancelled"

android - 在 angularjs/phonegap 中以不同的 url 开始

javascript - 带 for 语句的空表单

javascript - 获取 $http 调用的完整调用堆栈跟踪

jquery - 在 http 页面上使用 https 的 Ajax

android - Cordova Splashscreen 插件 - Android 上的空白屏幕而不是启动图像

android - Gradle错误:服务器返回HTTP响应代码:403的URL:http://services.gradle.org/distributions/gradle-2.2.1-all.zip