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

Cordova项目出现Failed to execute 'send' on 'XMLHttpRequest'错误求解决方案

问题根因

这个报错是Cordova Android端常见的XMLHttpRequest请求失败问题,核心触发原因包括:权限缺失、明文流量限制、内容安全策略拦截、白名单配置不全、同步XHR被内核限制。

解决方案
  • 1 配置网络权限
    确认AndroidManifest.xml中已经添加网络访问权限:
    <uses-permission android:name="android.permission.INTERNET" />
    
  • 2 开放明文流量权限(仅针对请求地址为HTTP协议的场景)
    Cordova Android 9.0+默认禁止HTTP明文请求,在项目根目录的config.xml的widget节点先添加命名空间:
    <widget id="xxx" version="xxx" xmlns:android="http://schemas.android.com/apk/res/android">
    
    再添加明文访问配置:
    <edit-config file="AndroidManifest.xml" mode="merge" target="/manifest/application">
        <application android:usesCleartextTraffic="true" />
    </edit-config>
    
  • 3 配置内容安全策略(CSP)
    在www/index.html的head节点添加CSP配置,将你请求的目标域名加入放行规则:
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' 替换为你的请求域名 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
    
    测试阶段可临时用通配符*代替域名,生产环境必须替换为实际业务域名避免安全风险
  • 4 配置白名单规则
    首先确认已经安装白名单插件:
    cordova plugin add cordova-plugin-whitelist
    
    再在config.xml中添加白名单规则:
    <access origin="*" />
    <allow-navigation href="*" />
    <allow-intent href="*" />
    
    生产环境同样需要将通配符替换为实际业务域名
  • 5 优化XHR请求逻辑
    你当前使用的是同步XHR(open方法第三个参数设为false),现代Chromium内核对同步请求有严格限制,很容易触发请求失败,建议改为异步请求:
    obtenirListeSentiers(callback){
        try{
            const xhttp = new XMLHttpRequest();
            xhttp.open("GET", "XXXX", true);
            xhttp.setRequestHeader("requete", "obtenirListeSentiers");
            xhttp.onload = () => {
                if(xhttp.status === 200){
                    this.listeSentiers = xhttp.responseText;
                    callback(null, this.listeSentiers);
                }else{
                    callback(new Error('请求失败'), null);
                }
            }
            xhttp.onerror = () => callback(new Error('网络错误'), null);
            xhttp.send();
        }
        catch(err){
            console.log(err.stack)
            callback(err, null);
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 14:15:08