当前位置: 首页 > news >正文

基于 xhr 实现 axios

基于 xhr 实现 axios

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

xhr 二次封装

src/plugins/xhr.js

/*** 请求拦截器队列* 响应拦截器队列*/
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)) returnlet 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

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)
}

调用

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)
})

在这里插入图片描述

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

在这里插入图片描述

原文链接:菜园前端

http://www.lryc.cn/news/144508.html

相关文章:

  • 基于面向对象的大模型代码生成
  • 易云维®FMCS厂务系统创造工厂全新的“数字低碳智能”应用场景
  • 【Linux应用部署篇】在CSDN云IDE平台部署Etherpad文档编辑器
  • 基于java swing和mysql实现的汽车租赁管理系统(源码+数据库+文档+运行指导视频)
  • Rigs-of-rods安装
  • html学习第2篇---标签(1)
  • 爬虫逆向实战(二十四)--某鸟记录中心
  • 【操作系统】中断和异常
  • 锁策略、原子编程CAS 和 synchronized 优化过程
  • 【WINAPI】文件读写操作问题
  • 【LeetCode-中等题】148. 排序链表
  • Ceph EC pg backfill run
  • 腾讯云服务器地域怎么选?广州上海北京?
  • Apple Configurator iphone ipad 设备管控 描述文件使用方法
  • Linux 管道(pipe)用法
  • 元素隐式具有 “any“ 类型,因为类型为 “string“ 的表达式不能用于索引类型
  • 34、springboot切换内嵌Web服务器(Tomcat服务器)与 生成SSL证书来把项目访路径从 HTTP 配置成 HTTPS
  • 3种CSS实现背景图片全屏铺满自适应的方式
  • M1 Pro 利用docker 搭建pytho2的开发环境,以vscode连接开发为例
  • MySQL概述,架构原理
  • Three.js实现模型,模型材质可拖拽效果 DragControls
  • 机器学习笔记之优化算法(二十)牛顿法与正则化
  • 【Go 基础篇】深入探索:Go语言中的切片遍历与注意事项
  • 一些经典的SQL语句
  • 〔018〕Stable Diffusion 之 批量替换人脸 篇
  • Unity字符串性能问题
  • 深入浅出SSD:固态存储核心技术、原理与实战(文末赠书)
  • 关于layui+php,三级联动-编辑回显的问题。
  • lua的函数
  • pytorch/tensorflow 直接给张量中的某个位置的值赋值,操作不可导。