ext-xhr-interceptor
TypeScript icon, indicating that this package has built-in type declarations

1.1.1 • Public • Published

XHR Interceptor

一个强大的 XMLHttpRequest 拦截器,支持请求和响应的拦截、修改和监听。使用 Proxy 技术实现,无需修改现有代码即可拦截所有 XHR 请求。

特性

  • 🚀 零侵入性: 使用 Proxy 技术,无需修改现有代码
  • 🎯 精确匹配: 支持字符串、正则表达式和数组匹配目标 URL
  • 🔧 灵活配置: 支持请求前修改、响应后处理、错误处理等
  • 📊 完整信息: 提供请求和响应的完整信息,包括 headers、query 参数等
  • 🛡️ 类型安全: 完整的 TypeScript 类型定义
  • 📦 轻量级: 无外部依赖,体积小巧

安装

NPM 安装

npm install ext-xhr-interceptor

或者使用 yarn:

yarn add ext-xhr-interceptor

CDN 引入

你也可以通过 script 标签直接在浏览器中使用:

<script src="https://unpkg.com/ext-xhr-interceptor@latest/dist/index.browser.js"></script>

或者下载到本地使用:

<script src="./path/to/index.browser.js"></script>

使用方法

ES 模块方式

import { interceptXHR } from 'ext-xhr-interceptor';

// 拦截所有包含 '/api' 的请求
interceptXHR({
  targetUrl: '/api',
  onRequest: (config) => {
    console.log('拦截到请求:', config);
  },
  onResponse: (response) => {
    console.log('拦截到响应:', response);
  }
});

Script 标签方式

<script src="https://unpkg.com/ext-xhr-interceptor@latest/dist/index.browser.js"></script>
<script>
// 通过全局变量 XHRInterceptor 访问
XHRInterceptor.interceptXHR({
  targetUrl: '/api',
  onRequest: (config) => {
    console.log('拦截到请求:', config);
  },
  onResponse: (response) => {
    console.log('拦截到响应:', response);
  }
});

// 或者使用解构赋值
const { interceptXHR } = XHRInterceptor;
interceptXHR({
  targetUrl: '/api',
  onRequest: (config) => {
    console.log('拦截到请求:', config);
  }
});
</script>

高级配置

import { interceptXHR } from 'ext-xhr-interceptor';

interceptXHR({
  // 支持多种匹配方式
  targetUrl: ['/api', /\.json$/, 'https://example.com'],
  
  // 请求前处理
  beforeRequest: (config) => {
    // 修改请求头
    config.headers['X-Custom-Header'] = 'value';
    
    // 修改请求体
    if (config.body) {
      config.body.extraField = 'extra value';
    }
    
    return config;
  },
  
  // 响应后处理
  afterResponse: (response) => {
    // 修改响应数据
    if (response.status === 200) {
      response.response.extraField = 'response value';
    }
    return response;
  },
  
  // 请求监听
  onRequest: (config) => {
    console.log('请求配置:', {
      method: config.method,
      url: config.url,
      headers: config.headers,
      body: config.body,
      query: config.query
    });
  },
  
  // 响应监听
  onResponse: (response) => {
    console.log('响应数据:', {
      status: response.status,
      headers: response.headers,
      response: response.response,
      matchedPattern: response.matchedPattern
    });
  },
  
  // 错误处理
  onError: (error, phase) => {
    console.error(`${phase}阶段发生错误:`, error);
  }
});

API 文档

interceptXHR(options: XHRInterceptorOptions)

参数

  • options.targetUrl: string | RegExp | Array<string | RegExp> - 目标 URL 匹配模式
  • options.beforeRequest?: (config: RequestConfig) => RequestConfig | Promise<RequestConfig> - 请求前处理函数
  • options.afterResponse?: (response: ResponseConfig) => ResponseConfig | Promise<ResponseConfig> - 响应后处理函数
  • options.onRequest?: (config: RequestConfig) => void - 请求监听函数
  • options.onResponse?: (response: ResponseConfig) => void - 响应监听函数
  • options.onError?: (error: Error, phase: 'request' | 'response') => void - 错误处理函数

类型定义

interface RequestConfig {
  method: any;
  url: string;
  query?: Record<string, string>;
  headers: Record<string, string>;
  body: any;
  withCredentials?: boolean;
}

interface ResponseConfig<T = any> {
  status: number;
  headers: Record<string, string>;
  response: T;
  matchedPattern: string | RegExp;
  requestConfig: RequestConfig;
}

使用场景

1. API 调试

interceptXHR({
  targetUrl: '/api',
  onRequest: (config) => {
    console.log('API 请求:', config);
  },
  onResponse: (response) => {
    console.log('API 响应:', response);
  }
});

2. 请求修改

interceptXHR({
  targetUrl: '/api/auth',
  beforeRequest: (config) => {
    // 自动添加认证头
    config.headers['Authorization'] = `Bearer ${getToken()}`;
    return config;
  }
});

3. 响应数据处理

interceptXHR({
  targetUrl: /\.json$/,
  afterResponse: (response) => {
    // 统一处理响应数据
    if (response.status === 200 && response.response.code === 0) {
      return response;
    } else {
      throw new Error(response.response.message || '请求失败');
    }
  }
});

4. 错误监控

interceptXHR({
  targetUrl: ['/api', '/v1'],
  onError: (error, phase) => {
    // 上报错误到监控系统
    reportError({
      type: 'xhr_error',
      phase,
      error: error.message,
      timestamp: Date.now()
    });
  }
});

注意事项

  1. 浏览器兼容性: 需要支持 Proxy 的现代浏览器
  2. 性能影响: 拦截器会对所有匹配的请求产生影响,建议合理设置匹配规则
  3. 内存泄漏: 长时间运行时注意清理不需要的监听器
  4. 调试模式: 生产环境建议关闭详细的日志输出

开发

# 安装依赖
npm install

# 开发模式
npm run dev

# 构建
npm run build

# 清理构建文件
npm run clean

许可证

MIT License

贡献

欢迎提交 Issue 和 Pull Request!

更新日志

v1.1.0

  • 🎉 新增 UMD 格式支持,现在可以通过 script 标签直接在浏览器中使用
  • 📦 添加 CDN 引入方式
  • 📚 更新文档,添加 script 标签使用示例

v1.0.0

  • 初始版本发布
  • 支持基本的 XHR 拦截功能
  • 提供完整的 TypeScript 类型定义

Package Sidebar

Install

npm i ext-xhr-interceptor

Weekly Downloads

26

Version

1.1.1

License

MIT

Unpacked Size

42.9 kB

Total Files

11

Last publish

Collaborators

  • chenng99999