Cordova中的jQuery AJAX调用无论超时设置如何都会在30秒后超时。

5
我将尝试在Android上执行以下函数,以与我正在制作的物联网设备同步:
function NewDeviceFetchDeviceID(){
    strURL = "https://192.168.x.x/.....";

    return $.ajax({
        url: strURL,
        type: 'GET',
        timeout: 90000
    });
}

该设备需要一些时间来生成对请求的响应(约为45-50秒),因此我需要超时时间略长于30秒。如果我在iOS上将超时设置为5秒,它会执行此操作;如果我将其设置为90秒,则会等待整个时间。但是,在Android上,似乎忽略了这个参数。
我尝试在<platform name="android">下添加以下配置到config.xml,但没有成功:
<preference name="LoadUrlTimeoutValue" value="90000"/>

我尝试使用小写的字母 "L",但仍然没有成功。
<preference name="loadUrlTimeoutValue" value="90000"/>

如何在 Cordova Android 应用程序中正确增加 AJAX 请求的超时参数?
更新: 我已更改函数,并确实在 30 秒后获得“已超时!!!”作为响应:
function TryXHR(){
    try{
        var xhr = new XMLHttpRequest();

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                alert("ready state = 4");
            }
        };

        strURL = "https://192.168.x.x/......";
        xhr.open("POST", strURL, true);
        xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
        xhr.timeout = 120000; // Set timeout to 120 seconds (120000 milliseconds)
        xhr.onload  = function () { alert(xhr.response); }
        xhr.ontimeout = function () { alert("Timed out!!!"); }
        xhr.onerror = function () { alert("Non-timeout error"); }
        xhr.send();
    }catch(err){
        alert("exception caught: "+err.message);
    }
}

服务器端没有超时限制。我可以看到服务器仍在解密来自移动应用程序的传入信息,但(安卓)移动应用程序已放弃。 - Lil' Bits
你尝试过使用 $.ajax 的 complete() 方法来触发回调函数吗?同时设置一个错误函数,以确保超时是 $ajax 的真正问题。可以使用 error() 方法中的 error: function(x, t, m) {if(t==="timeout") {alert("got timeout"); } else { alert(t); } } - Sim1-81
@Sim1-81,请查看原帖中的更新。 - Lil' Bits
你的服务器是否在负载均衡器后面? - karthick
@Lil' Bits,出于好奇,strURL = "https://192.168.x.x/......";似乎是本地环境,你确定可以在 HTTPS 下执行请求吗?这可能是一个协议问题。昨天我遇到了类似的 cUrl 请求问题,因为我的 API 服务器上的 SSL 证书未激活。 - Sim1-81
显示剩余5条评论
1个回答

3

经过一个月的挣扎,我最终使用了 Cordova Advanced HTTP 插件:https://www.npmjs.com/package/cordova-plugin-advanced-http

通过使用 setRequestTimeout 方法,我成功将HTTP请求超时时间增加到120秒:

cordova.plugin.http.setRequestTimeout(120.0);

将我的请求重写以利用这个插件后,我的问题在Android 9/10上得到了解决,并且在iOS 12/13上仍然按预期工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接