封装axios请求

ops/2024/10/20 15:56:08/

1、为什么要封装axios

封装axios,对错误信息进行统一处理,能提高代码简洁性,规范代码

2、封装步骤

2.1 创建文件

首先在utils文件夹下新建request.js文件,内容如下。要确保项目已经安装了axios,和element-ui

javascript">import store from '@/store'
import { getToken } from '@/utils/local'
import axios from 'axios'
import { Message } from 'element-ui'//生产环境请求接口地址
if (process.env.NODE_ENV === 'production') {// window.config.userCenter = `${window.location.origin}:8080`window.config.serveIp = `${window.location.origin}/api`window.config.serveUrl = `${window.location.origin}/api`
}
// create an axios instance
const service = axios.create({// baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url// withCredentials: true, // send cookies when cross-domain requestsbaseURL: window.config.serveUrl,timeout: 60000 // request timeout
})
const pending = []
const cancelToekn = axios.CancelToken
let removeP = false
const removePending = (config, isAll) => {for (let i = 0; i < pending.length; i++) {if (isAll) {pending[i].fun()pending.splice(i, 1)i--} else {if (pending[i].name === config.url + JSON.stringify(config.data) + '&' + config.method) {pending[i].fun()pending.splice(i, 1)break}}}
}
// request interceptor
service.interceptors.request.use(config => {// 在HTTP请求前取消前面的所有请求removeP = config.removePif (config.removeP) removePending(config, true)// 记录本次HTTP请求// eslint-disable-next-line new-capconfig.cancelToken = new cancelToekn((c) => {pending.push({name: config.url + JSON.stringify(config.data) + '&' + config.method,fun: c})})// do something before request is sent// 请求头添加tokenif (getToken()) {config.headers['Token'] = getToken()}return config},error => {// do something with request errorconsole.log(error) // for debugreturn Promise.reject(error)}
)
// response interceptor
service.interceptors.response.use(/*** If you want to get http information such as headers or status* Please return  response => response*//*** Determine the request status by custom code* Here is just an example* You can also judge the status by HTTP Status Code*/response => {if (response.status !== 200) {Message.error(response.data.message)} else {return response.data}},error => {if (error.response) {const { response: { status, data: { msg, code }}} = errorconst reloadCode = [1106, 1107, 1108]const waringCode =[1408]switch (status) {case 400:Message.error(msg)breakcase 401:// 返回 401 清除token信息并跳转到登录页面if (reloadCode.includes(code)) {setTimeout(() => {store.dispatch('user/resetToken').then(() => {location.reload()})}, 1000)}Message.error(msg)breakcase 403:Message.error(msg)breakcase 404:if(waringCode.includes(code)){Message.warning(msg)break}Message.error(msg)breakcase 408:error.message = '请求超时'breakcase 422:Message.error('参数错误')breakcase 500:error.message = '服务器内部错误'breakcase 501:error.message = '服务未实现'breakcase 502:// 连接服务器失败Message.error('服务器内部错误')setTimeout(() => {store.dispatch('user/resetToken').then(() => {location.reload()})}, 500)Message.error('服务器内部错误')error.message = '网关错误'breakcase 503:error.message = '服务不可用'breakcase 504:error.message = '网关超时'breakcase 505:error.message = 'HTTP版本不受支持'breakdefault:error.message = '连接服务器异常'}return error} else {if (removeP) {return}error.message = '连接服务器失败'Message.error('连接服务器失败')console.log(error.message)}}
)export default service

2.2 使用封装的request

首先对接口进行分类,例如商品接口,src下新建api文件夹,新建goods.js
首先要引入封装的request,然后导出

javascript">// 引入封装的request
import request from '@/utils/request'// 获取商品列表
export function getGoodsList(data) {return request({url: '/goods/list',method: 'get',data})
}

2.3 在组件中使用

javascript">// 首先按需引入使用的接口
import { getGoodsList } from "@/api/goods.js"

接口返回的是promise格式,可以用async await 或者.then.catch解析

javascript">// 然后在方法中直接使用
created() {this.getTableList()
},
methods: {getTableList() {let data= {page: 1,pagesize: 20}// 接口返回的时promisegetGoodsList(data).then(res=>{if(res.code == 200) {this.tableData = res.data}}).catch(error => {console.log(error);})}

http://www.ppmy.cn/ops/118393.html

相关文章

实现网上超市:SpringBoot技术详解

2 系统开发技术 这部分内容主要介绍本系统使用的技术&#xff0c;包括使用的工具&#xff0c;编程的语言等内容。 2.1 Java语言 Java语言自公元1995年至今&#xff0c;已经超过25年了&#xff0c;依然在软件开发上面有很大的市场占有率。当年Sun公司发明Java就是为了发展一门跨…

【C高级】有关shell脚本的一些练习

目录 1、写一个shell脚本&#xff0c;将以下内容放到脚本中&#xff1a; 2、写一个脚本&#xff0c;包含以下内容&#xff1a; 1、写一个shell脚本&#xff0c;将以下内容放到脚本中&#xff1a; 1、在家目录下创建目录文件&#xff0c;dir 2、dir下创建dir1和dir2 …

pytorch千问模型源码分析

# 规范化技术&#xff0c;旨在替代传统的 Layer Normalization&#xff08;LN&#xff09; # 核心思想是对输入张量的每个样本的每个特征进行规范化&#xff0c;使其均值为 0&#xff0c;方差为 1 class Qwen2RMSNorm(nn.Module): def __init__(self, hidden_size, eps1e-6…

聚势启新 智向未来 | 重庆华阳通用科技有限公司揭牌成立

助推两江新区汽车产业高质量发展 (以下文字内容转载自两江新区网&#xff09; 9月26日&#xff0c;重庆华阳通用科技有限公司&#xff08;华阳通用重庆子公司&#xff09;在两江新区揭牌成立&#xff0c;将致力于智能座舱、智能驾驶两大领域&#xff0c;不断加大技术研发投入…

Spring Boot与GraphQL:现代化API设计

引言 在当今的软件开发领域&#xff0c;构建高效、灵活且易于维护的API是至关重要的。随着微服务架构的流行&#xff0c;RESTful API已经成为Web服务的标准方式之一。然而&#xff0c;随着应用程序变得越来越复杂&#xff0c;REST API的一些局限性开始显现出来。例如&#xff…

Python NumPy 数据清洗:高效处理数据异常与缺失

Python NumPy 数据清洗&#xff1a;高效处理数据异常与缺失 文章目录 Python NumPy 数据清洗&#xff1a;高效处理数据异常与缺失一 数据预处理的常见问题二 待处理的数据三 数据预处理四 清洗数据1 查看第一列学号2 查看第二列年龄结果解析函数解释1&#xff09;~np.isnan(dat…

美团中间件C++一面-面经总结

1、TCP和UDP 的区别&#xff1f; 速记标识符&#xff1a;连靠刘墉宿营 解释&#xff1a; 面向连接vs无连接 可靠传输vs不保证可靠 字节流vs报文传输 拥塞控制流量控制vs无 速度慢vs速度快 应用场景自己描述 2、服务端处于close wait是什么情况&#xff0c;是由什么造成的&…

FortiOS SSL VPN 用户访问权限配置

简介 使用不同用户组或用户登录 SSL VPN 隧道模式后&#xff0c;可配置不同的访问权限。 本文介绍为不同用户组分配不同访问权限的配置方法。 相关组件 FortiGate&#xff1a;FortiOS v6.4.14 build2093 (GA) 客户端&#xff1a;Windows11&#xff0c;安装 FortiClient VPN 7.…