是否有一个事件会在 Node.js 的 XMLHttpRequest 模块成功或出错时运行?根据docs , onloadend 事件应该在错误和成功时触发,但它仅在成功时运行。例如:
var XMLHttpRequest = require( 'xmlhttprequest' ).XMLHttpRequest;
var url = 'https://www.example-bad-url.com/json.php';
var xhr = new XMLHttpRequest();
xhr.open( 'GET', url );
xhr.send();
xhr.onloadend = function() {
// This should get logged, but it doesn't.
console.log( 'The request has completed, whether successfully or unsuccessfully.' );
}
在上面的脚本中,onloadend没有运行,为什么? URL不存在,所以它应该触发onloadend作为错误并记录“请求已完成...”,但回调函数从未运行,为什么?
最佳答案
node.js 的 xmlhttprequest
库未完全正确地实现规范。
如果我们深入 github 上的代码,我们会看到以下代码行:
if (self.readyState === self.DONE && !errorFlag) {
self.dispatchEvent("load");
// @TODO figure out InspectorInstrumentation::didLoadXHR(cookie)
self.dispatchEvent("loadend");
}
因此,只有在没有错误时才会触发 load
和 loadend
事件处理程序,这与我们的观察结果一致
xhr.onloadend = function() {
// This should get logged, but it doesn't.
console.log( 'The request has completed.' );
};
仅在事件成功时才会记录。
我的建议是在 .onerror()
处理程序中手动触发该事件,这确实有效。请记住,这是第 3 方 Node.js 模块,而不是 native 模块。
我个人只是围绕 xmlhttprequest 编写了一个小包装器,模仿 .fetch()
接口(interface)。 Node.js 版本使用原生 Node.js http
库,客户端版本使用 xmlhttprequest。
这样我就可以对前端和后端代码使用相同的 .fetch()
API,并让系统决定是否使用 native 获取、xmlhttp 支持的获取,或者http 驱动的获取。
关于javascript - XMLHttpRequest onloadend 事件因错误而未运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58169480/