Vue回炉重造之三次封装axios

2022-05-17 18:22:40 浏览数 (1)

源码目录

在src目录下建立一个request文件夹。里面建立两个文件:

代码语言:javascript复制
http.js
api.js
12

源码内容

http.js

import axios from ‘axios’ // 引入axios import store from ‘…/store/index’ // 引入Vuex import router from ‘…/router’ // 引入vue-router import { Message } from ‘element-ui’ //局部引入UI框架组件 // 环境的切换 if (process.env.NODE_ENV === ‘development’) { axios.defaults.baseURL = ‘https://xxx/’ // 开发环境 } else if (process.env.NODE_ENV === ‘debug’) { axios.defaults.baseURL = ‘’ // 调试环境 } else if (process.env.NODE_ENV === ‘production’) { axios.defaults.baseURL = ‘https://xxx/’ // 生产环境 } axios.defaults.timeout = 10000; // 请求拦截器 axios.interceptors.request.use( config => { if (localStorage.getItem(‘Authorization’)) { config.headers.Authorization = Bearer " " localStorage.getItem(‘Authorization’); //查看是否存在token return config; } else if (config.isUpload) { config.headers = { ‘Content-Type’: ‘multipart/form-data’} // 根据参数是否启用form-data方式 return config; } else { config.headers = { ‘Content-Type’: ‘application/json’ } return config; } }, error => { return Promise.error(error) })

// 响应拦截器 axios.interceptors.response.use( // 服务码是200的情况 response => { if (response.status === 200) { switch (response.data.code) { // 未登录 case 3: Message({ message: ‘未登录’, type: ‘error’, offset:380, duration:1000 }); // 清除登录状态,返回首页 localStorage.removeItem(‘Authorization’) localStorage.removeItem(‘info’) store.commit(“changeNull”) if (router.app._route.name != ‘home’) { setTimeout(() => { router.push({ path: ‘/’, }) }, 1000) } break; // 课程已添加 case 100: Message({ message: ‘课程已添加’, type: ‘error’, offset:380, duration:1000 }); break; // token过期 case 5: Message({ message: ‘登录过期,请重新登录’, type: ‘error’, offset:380, duration:1000 });

更多内容请见原文,原文转载自:https://blog.csdn.net/weixin_44519496/article/details/119116763

0 人点赞