UNPKG

xlb-main-login

Version:

``` yarn install ```

82 lines (71 loc) 2.29 kB
import axios from 'axios' import storage from '@/store' import notification from 'ant-design-vue/lib/notification' import { VueAxios } from './axios' import { ACCESS_TOKEN } from '@/store/mutation-types' import { message } from 'ant-design-vue' import Vue from 'vue' // 创建 axios 实例 const request = axios.create({ // API 请求的默认前缀 baseURL: process.env.VUE_APP_API_ROOT, timeout: 12000 * 2 // 请求超时时间 }) // 异常拦截处理器 const errorHandler = (error) => { if (error.response) { const data = error.response.data // 从 localstorage 获取 token if (error.response.status === 403) { notification.error({ message: 'Forbidden', description: data.msg }) } if (error.response.status === 401 && !(data.result && data.result.isLogin)) { notification.error({ message: '暂无权限', description: '暂无权限,如有需求,请联系组长处理' }) } message.error(data.msg) } return Promise.reject(error) } // request interceptor request.interceptors.request.use(config => { if (config.url.includes('{')) { // 替换占位符 const reg = /{.+?}/g const regExpMatchArray = config.url.match(reg) if (regExpMatchArray) { regExpMatchArray.forEach(e => { const key = e.substring(1, e.length - 1) config.params && (config.url = config.url.replace('{' + key + '}', config.params[key])) config.params && delete config.params.key config.data && (config.url = config.url.replace('{' + key + '}', config.data[key])) config.data && delete config.data.key }) } } const token = window.sessionStorage.getItem('access_token') || Vue.ls.get(ACCESS_TOKEN) if (token) { config.headers.common['Authorization'] = 'Bearer ' + token // 让每个请求携带自定义 token 也可以使用cookie } return config }, errorHandler) // response interceptor request.interceptors.response.use((response) => { return response.data }, errorHandler) const installer = { vm: {}, install (Vue) { Vue.use(VueAxios, request) } } export default request export { installer as VueAxios, request as axios }