12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- // 引入接口
- import initApi from '@/apis/index'
- import Vue from 'vue'
- import { Dialog, Toast } from 'vant'
- export default function (context) {
- const { $axios, redirect, store } = context
- // 初始化接口及挂载接口
- const apiMap = initApi($axios)
- Vue.prototype.$http = context.$http = { api: apiMap }
- // 设置请求头
- $axios.onRequest(() => {
- $axios.setHeader('X-Token', store.getters.accessToken)
- })
- // 响应拦截
- $axios.onResponse(async (response) => {
- const res = response.data
- // 请求成功
- if (!res.code) return res
- // 请求失败
- if (res.code === -1) {
- console.log(store.getters.routePrefix)
- Toast(res.msg || '服务器开小差了')
- if (res.msg.indexOf('code been used') > -1) {
- try {
- redirect(store.getters.routePrefix)
- } catch (error) {
- console.log(error)
- }
- }
- }
- // 登录过期
- if (res.code === -99) {
- const result = await Dialog.alert({
- title: '提示',
- message: '登录已过期,请重新登录',
- theme: 'round-button',
- confirmButtonColor: 'linear-gradient(to left, #404040, #101010)',
- })
- Vue.prototype.$removeStorage(store.getters.routePrefix, 'userInfo')
- store.dispatch('user/logout')
- if (result === 'confirm') {
- redirect(store.getters.routePrefix)
- }
- }
- return Promise.reject(res)
- })
- // 错误拦截
- $axios.onError((error) => {
- const code = parseInt(error.response && error.response.status)
- if (code === 400) {
- redirect('/400')
- }
- })
- }
|