我有一个正在运行的 node.js 服务器,并且我正在通过 jquery 对该服务器进行一系列 ajax 调用。其中一个 ajax 调用预计需要大约 5 分钟才能完成。我发现在调用电话时,总是在 4 分钟后超时,并出现错误“net::ERR_EMPTY_RESPONSE”。我见过类似以下的问题:ajax net::ERR_EMPTY_RESPONSE after waiting for response for 2 mins - node.js server但无论我是否设置了超时参数(要么设置为 0,这意味着 jquery 中的“无超时”,要么将其设置为大于 4 分钟的值,例如 300000,即 5 分钟。),都会发生这种情况。每次都会在 4 分钟内准时发生。
有人知道为什么会发生这种情况吗? ajax jquery 调用是否有上限,它们可以花费多长时间 - 无论设置什么超时参数?
这是进行 ajax 调用的代码:
(此 try block 位于一个函数中,该函数的目的是对特定 URL 进行 ajax 调用。url
、jsonToSend
和 timeout
code> 都是该函数的参数。(具体来说,timeout
是一个 int,一个以毫秒为单位的数字,用于在调用超时之前等待)
try {
var ajaxCallConfig = {
method: action,
url: url,
data: jsonToSend,
contentType: "application/json",
success: function (ret) {
deferred.resolve(ret);
},
error: function (xhr, textStatus, errorThrown) {
// I ALWAYS end up in this block, with a net::ERR_EMPTY_RESPONSE being thrown, when I call this function to the long running api endpoint
console.log("Error on Ajax call to " + url + "; json " +
JSON.stringify(jsonToSend) +
"; text status: " + textStatus +
"; error thrown: " + JSON.stringify(xhr));
// check if it was a timeout
if (textStatus === 'timeout') {
// some error handling my server does specific to timeouts...
// left it out as it's not relevant...
// note : never hit this block, when the net::ERR_EMPTY_RESPONSE issue happens. (when i call the long-running api)
// but I hit this block if i give some dummy low value to the 'timeout' param to force a timeout.
}
else {
if (xhr.responseJSON) {
// under this case, server sent the response and set
// the status code
deferred.reject(xhr.responseJSON);
}
else {
// under this case, the error status is not set by
// server, it may due to other reasons
deferred.reject("Connection Error: " +
" Connection to server cannot be established");
}
}
}
};
if (typeof timeout !== 'undefined') {
console.log("set a timeout of " + timeout); // timeout is definitely being set, as I see this in console logs
ajaxCallConfig.timeout = timeout; // timeout attr does work , because when I try this with a very low number, say 300, it times out immediately
}
jQuery.ajax(ajaxCallConfig); // here we're making the ajax call
}
//catch block ,函数的其余部分..
最佳答案
正如@MadWard 的回答 - 我希望将其发布在这里,以防其他人偶然发现这一点!正在运行的nodejs服务器(ajax正在向其发送ajax调用)似乎有4分钟的默认超时。因此,无论我为 jquery 指定多少超时来进行调用,如果调用时间超过 4 分钟,服务器本身就会出错。
由于这是我自己的服务器,因此我可以通过简单地增加nodejs服务器本身的“超时”属性来解决这个问题。这是一个示例(来自定义 Nodejs 服务器的文件):
var server = app.listen(serverPort, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
});
server.timeout = 600000; // this was not set before. The default appeared to have been 4 minutes. Setting this fixed it! (NOTE this should be in milliseconds - so this is 10 minutes!)
关于jquery - 即使设置了超时,也无法使 jQuery ajax 调用持续超过 4 分钟,并出现 net::ERR_EMPTY_RESPONSE 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54526602/