You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cordova开发的iOS App请求HTTP接口始终返回400 Bad Request问题

Cordova iOS 端 HTTP 请求拦截问题解决方案

1. 确保 NSAppTransportSecurity (ATS) 配置正确生效

直接修改 info.plist 可能会被 Cordova 构建过程覆盖,建议通过 config.xml 注入配置,确保每次构建都能应用:

<platform name="ios">
    <config-file parent="NSAppTransportSecurity" target="*-Info.plist">
        <dict>
            <!-- 允许所有 HTTP 请求(测试环境可用,上线需按需配置) -->
            <key>NSAllowsArbitraryLoads</key>
            <true/>
            <!-- 如果是指定域名,替换成以下配置 -->
            <!--
            <key>NSExceptionDomains</key>
            <dict>
                <key>your-api-domain.com</key>
                <dict>
                    <key>NSIncludesSubdomains</key>
                    <true/>
                    <key>NSAllowsArbitraryLoads</key>
                    <true/>
                </dict>
            </dict>
            -->
        </dict>
    </config-file>
</platform>

2. 修正 AllowCleartextTraffic 配置范围

将该偏好设置放在 iOS 平台专属配置内,避免全局配置不生效:

<platform name="ios">
    <preference name="AllowCleartextTraffic" value="true" />
</platform>

3. 排查 XMLHttpRequest 使用问题

  • 确认请求 URL 完整(必须带 http:// 前缀,不能省略);
  • 检查后端是否配置了正确的 CORS 规则,可通过 Chrome 开发者工具模拟 Cordova 环境(修改 User-Agent),查看请求是否存在跨域错误;
  • 尝试替换为 Cordova 专用 HTTP 插件:cordova-plugin-advanced-http,它对系统请求限制的兼容性更好,示例代码:
cordova.plugin.http.get('http://your-api-url.com', {}, {}, function(response) {
    console.log(response.data);
}, function(error) {
    console.error(error);
});

4. 清理构建缓存并重新编译

旧配置残留可能导致修改不生效,执行以下命令彻底清理后重新构建:

cordova clean ios
cordova build ios --verbose

查看构建日志,确认 ATS 和 AllowCleartextTraffic 配置已正确写入 info.plist。

5. 适配 iOS 版本规则

iOS 10+ 对 ATS 限制更严格,iOS 13+ 使用 NSAllowsArbitraryLoads 时,App Store 审核可能需要提供合规说明(测试阶段可忽略)。

内容的提问来源于stack exchange,提问作者bramastaVic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 16:27:11