2023年8月1日发(作者:)
页封装(vue3)// axios封装import axios from 'axios'import store from '@/store'import router from '@/router'// 实例化// 1. baseURL// 2. 超时时间// 3. ⼤数处理const instance = ({ baseURL: '/', // 接⼝根地址 timeout: 5000 // 超时时间})// 拦截器// 1.请求拦截器 全局注⼊((config) => { // 在发送请求之前做些什么 // 从store⾥⾯拿到当前的⽤户token 放到请求headers中 // 1. 获取token const token = // 2. 请求头设置token if (token) ization = `Bearer ${token}` return config}, (error) => { // 对请求错误做些什么 return (error)})// 2.响应拦截器// 1. token失效 401 跳转到登录页// 2. 当后端接⼝不是以http 200 - 300 ⽽是通过⾃定义字段展⽰⼀个接⼝的成功状态// success -> true// 添加响应拦截器((response) => { // 对响应数据做点什么 200 -300 return response}, (e) => { // 对响应错误做点什么 除了200 - 300 // 如果是401 token失效 跳回到登录页 if (se && === 401) { // route 内置了转码操作 const redirectUrl = encodeURIComponent(th) ('/login?redirectUrl=' + redirectUrl) } return (e)})// 封装⼀个通⽤的函数 帮助⽤户解决get post 传参形式的不⼀样// axios get -> params post -> data/** * @description: 请求函数 * @param {*} url 请求地址 * @param {*} method 请求⽅法 GET/POST * @param {*} reqData 请求参数 Object * @return {*} Promise */export default function request (url, method, reqData) { return instance({ url, method, [rCase() === 'get' ? 'params' : 'data']: reqData })}
2023年8月1日发(作者:)
页封装(vue3)// axios封装import axios from 'axios'import store from '@/store'import router from '@/router'// 实例化// 1. baseURL// 2. 超时时间// 3. ⼤数处理const instance = ({ baseURL: '/', // 接⼝根地址 timeout: 5000 // 超时时间})// 拦截器// 1.请求拦截器 全局注⼊((config) => { // 在发送请求之前做些什么 // 从store⾥⾯拿到当前的⽤户token 放到请求headers中 // 1. 获取token const token = // 2. 请求头设置token if (token) ization = `Bearer ${token}` return config}, (error) => { // 对请求错误做些什么 return (error)})// 2.响应拦截器// 1. token失效 401 跳转到登录页// 2. 当后端接⼝不是以http 200 - 300 ⽽是通过⾃定义字段展⽰⼀个接⼝的成功状态// success -> true// 添加响应拦截器((response) => { // 对响应数据做点什么 200 -300 return response}, (e) => { // 对响应错误做点什么 除了200 - 300 // 如果是401 token失效 跳回到登录页 if (se && === 401) { // route 内置了转码操作 const redirectUrl = encodeURIComponent(th) ('/login?redirectUrl=' + redirectUrl) } return (e)})// 封装⼀个通⽤的函数 帮助⽤户解决get post 传参形式的不⼀样// axios get -> params post -> data/** * @description: 请求函数 * @param {*} url 请求地址 * @param {*} method 请求⽅法 GET/POST * @param {*} reqData 请求参数 Object * @return {*} Promise */export default function request (url, method, reqData) { return instance({ url, method, [rCase() === 'get' ? 'params' : 'data']: reqData })}
发布评论