基于 xhr 实现 axios

基于 xhr 实现 axios

上面我们讲到二次封装 axios ,但是现在我们尝试完全脱离 axios,自己实现一个 axios,由于 axios 底层是基于 xhr 做了二次封装,所以我们也可以尝试一下。

xhr 二次封装

src/plugins/xhr.js

javascript 复制代码
/**
 * 请求拦截器队列
 * 响应拦截器队列
 */
const request = []
const response = []

/**
 * xhr 封装
 */
function axios(config) {
    return new Promise((resolve) => {
        request.forEach((fn) => (config = fn(config)))

        const { method, url, data, headers } = config

        /**
         * 新建请求
         */
        const xhr = new XMLHttpRequest()
        xhr.open(method, url)

        /**
         * 设置请求头
         */
        for (const key in headers) {
            xhr.setRequestHeader(key, headers[key])
        }

        /**
         * 发送请求
         */
        xhr.send(data)

        /**
         * 监听返回值
         */
        xhr.onreadystatechange = () => {
            if (!(xhr.readyState === 4 && xhr.status === 200)) return

            let data = JSON.parse(xhr.responseText)

            response.forEach((fn) => (data = fn(data)))

            resolve(data)
        }
    })
}

/**
 * 拦截器定义
 */
axios.interceptors = {
    request: {
        use: (fn) => {
            request.push(fn)
        }
    },
    response: {
        use: (fn) => {
            response.push(fn)
        }
    }
}

export default axios

axios 二次封装

src/plugins/axios.js

javascript 复制代码
import axios from './xhr'
import qs from 'qs'

/**
 * 请求拦截器
 */
axios.interceptors.request.use((config) => {
    config.data = qs.stringify(config.data)

    return config
})

/**
 * 响应拦截器
 */
axios.interceptors.response.use((response) => {
    if (response.code !== 200) {
        alert('接口响应失败')
    }

    return response
})

/**
 * 接口请求方法
 */
const request = (method, option) => {
    return axios({
        method: method,
        url: 'https://study.noxussj.top' + option.url,
        data: option.data,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
}

export default {
    get: (option) => request('get', option),
    post: (option) => request('post', option),
    put: (option) => request('put', option)
}

调用

javascript 复制代码
import axios from './plugins/axios.js'

/**
 * 发起请求
 */
const p1 = axios.post({
    url: '/api/login',
    data: { account: 'test', password: '123456' }
})

p1.then((res) => {
    console.log(res.data)
})

修改后预览效果,依然是可以正常请求接口。

原文链接:菜园前端

相关推荐
嵌入式小企鹅1 分钟前
蓝牙学习系列(八):BLE L2CAP 协议详解
网络·学习·蓝牙·ble·协议栈·l2cap
王夏奇4 分钟前
python中的__all__ 具体用法
java·前端·python
叫我一声阿雷吧35 分钟前
JS 入门通关手册(45):浏览器渲染原理与重绘重排(性能优化核心,面试必考
javascript·前端面试·前端性能优化·浏览器渲染·浏览器渲染原理,重排重绘·reflow·repaint
大家的林语冰1 小时前
《前端周刊》尤大开源 Vite+ 全家桶,前端工业革命启动;尤大爆料 Void 云服务新产品,Vite 进军全栈开发;ECMA 源码映射规范......
前端·javascript·vue.js
jiayong231 小时前
第 8 课:开始引入组合式函数
前端·javascript·学习
田八1 小时前
聊聊AI的发展史,AI的爆发并不是偶然
前端·人工智能·程序员
广州灵眸科技有限公司1 小时前
为RK3588注入澎湃算力:RK1820 AI加速卡完整适配与评测指南
linux·网络·人工智能·物联网·算法
zhanghongbin011 小时前
AI 采集器:Claude Code、OpenAI、LiteLLM 监控
java·前端·人工智能
IT_陈寒1 小时前
Python的列表推导式里藏了个坑,差点让我加班到凌晨
前端·人工智能·后端
byoass1 小时前
csdn_upload_005
网络·安全·云计算