Skip to content

手写简易axios类

功能实现

  • 支持GET/POST/PUT/DELETE请求
  • 支持请求参数配置(URL参数、请求体参数)
  • 支持响应数据解析(JSON/XML/文本等)
  • 支持拦截器(请求前、响应后)
代码展示
js
// 简易axios类
class Axios {
    constructor() {
        this.interceptors = {
            request: [],
            response: []
        }
    }
    request(config) {
        const { method = 'GET', url, params = {}, data = {} } = config
        return new Promise((resolve, reject) => {
        // 请求拦截器
        this.interceptors.request.forEach(interceptor => {
            config = interceptor(config)
        })
        const xhr = new XMLHttpRequest()
        xhr.open(method, `${url}?${new URLSearchParams(params)}`, true)
        xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    resolve(JSON.parse(xhr.responseText))
                } else {
                    reject(new Error(xhr.statusText))
                }
            }
        }
        xhr.send(JSON.stringify(data))
        // 响应拦截器
        this.interceptors.response.forEach(interceptor => {
            interceptor(xhr.responseText)
        })
    })
    Get(url, params = {}) {
        return this.request({ method: 'GET', url, params })
    }
    Post(url, data = {}) {
        return this.request({ method: 'POST', url, data })
    }
    Put(url, data = {}) {
        return this.request({ method: 'PUT', url, data })
    }
    Delete(url, params = {}) {
        return this.request({ method: 'DELETE', url, params })
    }
}