Skip to content

HTTP 客户端库 源代码导览

项目结构

axios 的源代码结构:

axios/
├── lib/
│   ├── index.js    # 主入口
│   └── utils.js    # 工具函数
└── index.js         # 导出

核心文件

1. index.js - 主入口

主入口文件导出核心功能:

javascript
module.exports = axios;

2. lib/index.js - 核心实现

核心实现的主要逻辑:

javascript
function axios(data, options) {
  // 默认选项
  const opts = options || {};
  
  // 处理逻辑
  const result = process(data, opts);
  
  return result;
}

关键函数

1. request() - 发送请求

发送 HTTP 请求:

javascript
function request(config) {
  // 创建 Promise
  return new Promise((resolve, reject) => {
    // 创建 XMLHttpRequest
    const xhr = new XMLHttpRequest();
    
    // 配置请求
    xhr.open(config.method, config.url);
    
    // 设置请求头
    Object.keys(config.headers).forEach(key => {
      xhr.setRequestHeader(key, config.headers[key]);
    });
    
    // 处理响应
    xhr.onload = () => {
      const response = {
        data: JSON.parse(xhr.responseText),
        status: xhr.status,
        statusText: xhr.statusText,
        headers: parseHeaders(xhr.getAllResponseHeaders())
      };
      resolve(response);
    };
    
    // 处理错误
    xhr.onerror = () => {
      reject(new Error('Request failed'));
    };
    
    // 发送请求
    xhr.send(config.data);
  });
}

2. interceptors - 拦截器

请求和响应拦截器:

javascript
const interceptors = {
  request: [],
  response: []
};

function useRequestInterceptor(onFulfilled, onRejected) {
  interceptors.request.push({ onFulfilled, onRejected });
}

function useResponseInterceptor(onFulfilled, onRejected) {
  interceptors.response.push({ onFulfilled, onRejected });
}

3. cancelToken() - 取消请求

取消正在进行的请求:

javascript
function cancelToken(executor) {
  let cancel;
  
  const token = {
    promise: new Promise((resolve) => {
      cancel = resolve;
    })
  };
  
  executor(cancel);
  
  return token;
}

设计模式

1. 工厂模式

使用工厂模式创建实例:

javascript
function axios(options) {
  return new Instance(options);
}

2. 策略模式

使用策略模式处理不同情况:

javascript
function process(data, strategy) {
  return strategy(data);
}

总结

axios 的源代码简洁而高效,通过模块化的设计和清晰的接口,实现了强大的功能。理解其源代码有助于我们更好地使用和定制 axios。


架构师AI杜公众号二维码

扫描二维码关注"架构师AI杜"公众号,获取更多技术内容和最新动态