javascript - XMLHttpRequest onloadend 事件因错误而未运行

标签 javascript node.js xmlhttprequest

是否有一个事件会在 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");
  }

因此,只有在没有错误时才会触发 loadloadend 事件处理程序,这与我们的观察结果一致

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/

相关文章:

javascript - msie 奇怪的 div 格式(以及其他问题)我做错了什么?

javascript - 具有不同输入速度的嵌套 AJAX

javascript - 找不到模块 './fonoapi.node.js',但列出时会显示该模块

javascript - ReactJS 多文件上传和 axios post : Uncaught (in promise) SyntaxError:

javascript - 如何在 wordpress 中使页脚宽度负责(主题二十十三)

node.js - 在Windows7上安装node-weak时出错

node.js - AWS EC2 Angular 5 ng 服务未通过浏览器连接

angularjs - 为什么即使添加 CORS 后,我仍然在 http 请求中收到状态代码 403?

Python 将 Ajax 请求与普通页面 View 分开

javascript - 如何使用 Javascript 轻松监听 xhr 请求?