为了账号安全,请及时绑定邮箱和手机立即绑定

XMLHttpRequest onloadend 事件未运行出错

XMLHttpRequest onloadend 事件未运行出错

HUX布斯 2021-11-04 10:46:33
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 作为错误并记录“请求已完成...”但回调函数从未运行,为什么?
查看完整描述

1 回答

?
噜噜哒

TA贡献1784条经验 获得超7个赞

xmlhttprequestnode.js的库没有完全正确地实现规范。


如果我们深入研究 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()处理程序中手动触发事件,这确实有效。请记住,这是一个 3rd 方 node.js 模块,而不是原生模块。


就个人而言,我只是围绕 xmlhttprequest 编写了一个模拟.fetch()接口的小包装器。node.js 版本使用原生 node.jshttp库,客户端版本使用 xmlhttprequest。


这样我就可以.fetch()对前端和后端代码使用相同的API,让系统决定它是使用本机提取、xmlhttp 支持的提取还是 http 支持的提取。


查看完整回答
反对 回复 2021-11-04
  • 1 回答
  • 0 关注
  • 953 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信