You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用纯JS拦截XMLHttpRequest并伪造200状态响应?

拦截XMLHttpRequest并伪造200响应的实现方案

问题描述

我四处搜索该问题但结果不一。出于测试目的,我必须使用纯JavaScript拦截XMLHttpRequest并伪造后端返回的200状态响应。我已写出如下代码:

const originalXHROpen = window.XMLHttpRequest.prototype.open;
const originalXHRSend = window.XMLHttpRequest.prototype.send;

window.XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  this.interceptRequest = url.includes('foo/bar');
  originalXHROpen.apply(this, arguments);
};

window.XMLHttpRequest.prototype.send = function (data) {
  if (this.interceptRequest) {
    console.log('## INTERCEPTED REQUEST');
    // somehow fake a 200 response
    return;
  }

  originalXHRSend.apply(this, arguments);
};

目前我能拦截请求,但无法伪造200状态响应。请问这是否可行?若可行该如何实现?

可行,具体实现方法如下

要伪造200响应,需要手动模拟XMLHttpRequest的状态变化流程,设置响应属性并触发对应的事件,匹配真实请求的执行逻辑。修改后的完整代码如下:

const originalXHROpen = window.XMLHttpRequest.prototype.open;
const originalXHRSend = window.XMLHttpRequest.prototype.send;

window.XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  this.interceptRequest = url.includes('foo/bar');
  // 保存实例上的原始事件处理函数,避免拦截后原有逻辑失效
  this._originalOnLoad = this.onload;
  this._originalOnReadyStateChange = this.onreadystatechange;
  originalXHROpen.apply(this, arguments);
};

window.XMLHttpRequest.prototype.send = function (data) {
  if (this.interceptRequest) {
    console.log('## INTERCEPTED REQUEST');
    
    // 自定义伪造的响应内容,可按需修改
    const fakeResponse = {
      status: 200,
      statusText: 'OK',
      responseText: JSON.stringify({ code: 200, msg: '伪造的成功响应' }),
      readyState: 4 // 对应XHR的DONE状态
    };

    // 把伪造的响应属性赋值给当前XHR实例
    Object.assign(this, fakeResponse);
    // 如果需要支持responseType为json,额外设置response属性
    this.response = JSON.parse(fakeResponse.responseText);

    // 异步触发事件,模拟真实XHR的异步行为
    setTimeout(() => {
      // 触发readystatechange事件(如果有监听)
      if (typeof this._originalOnReadyStateChange === 'function') {
        this._originalOnReadyStateChange.call(this);
      }
      // 触发load事件(如果有监听)
      if (typeof this._originalOnLoad === 'function') {
        this._originalOnLoad.call(this);
      }
      // 触发loadend事件,还原完整的请求结束流程
      this.dispatchEvent(new Event('loadend'));
    }, 0);

    return;
  }

  originalXHRSend.apply(this, arguments);
};

关键细节说明

  • 响应属性赋值:直接给XHR实例设置status、responseText、readyState等核心属性,模拟真实响应的状态参数。
  • 事件触发逻辑:用setTimeout异步触发事件,和真实XHR的异步状态变化逻辑保持一致,确保调用方的事件监听代码能正常执行。
  • 原始事件保存:提前备份实例上的onload、onreadystatechange等事件处理函数,避免拦截操作覆盖原有业务逻辑。

内容的提问来源于stack exchange,提问作者CH4B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 18:45:10