监听 Ajax 调用的 500 个响应?

问题描述

我正在侦听网页上的 xhr 事件,以捕获任何可能的请求失败。为了收听所有这些,我正在应用这个伪猴子补丁:

var reqOpen = XMLHttpRequest.prototype.open;

XMLHttpRequest.prototype.open = function() {
this.addEventListener('load',function() {

console.log(this.readyState); // this is always 4,but I'm trying to 
listen for when it's not successful
console.log(this.responseText); //the respoinse

});

reqOpen.apply(this,arguments);

它在成功响应时起作用,但除此之外它不会捕获任何东西。

有什么方法可以尝试捕获不成功的请求(特别是返回 500 响应的请求?

谢谢

解决方法

load 事件仅在请求成功完成时触发。 onreadystatechange 事件将在请求过程的每一步触发。

在该事件处理程序中,检查 readyState4,这意味着请求已完成,无论成功与否。然后检测 status 属性是否为 500。此属性将是您要查找的 HTTP 响应代码。

不会有有效负载,因为服务器无法发回响应,从而使 responseText 无用。而是检查 statusText 属性以获取与 HTTP 状态对应的消息。

var reqOpen = XMLHttpRequest.prototype.open;

XMLHttpRequest.prototype.open = function() {
  this.addEventListener('readystatechange',function() {
    if (this.readyState === 4 && this.status === 500) {
      console.log(this.statusText);
    }
  });

  reqOpen.apply(this,arguments);
}
,

您可以在 status 事件或 load 事件中访问 loadend

本演示中使用的端点返回 500

var reqOpen = XMLHttpRequest.prototype.open;

XMLHttpRequest.prototype.open = function() {
  this.addEventListener('loadend',function() {
     if(this.status > 200){
        console.log('Loadend Status:',this.status)
     }      
  });
  this.addEventListener('load',function() {
    console.log('Load Status:',this.status)
  });
  reqOpen.apply(this,arguments);
}

// example making request with jQuery ajax that uses XMLHTtpRequest
$.get('https://httpstat.us/500')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>