| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126 |
- import axios from 'axios'
- import { MessageBox, Message } from 'element-ui'
- import store from '@/store'
- // create an axios instance
- const service = axios.create({
- baseURL: process.env.VUE_APP_BASE_API,
- withCredentials: true, // send cookies when cross-domain requests
- timeout: 10000 // request timeout
- })
- const CancelToken = axios.CancelToken
- let source = null
- function getCancelToken () {
- if (!source) {
- source = CancelToken.source()
- }
- return source.token
- }
- export function cancelRequest () {
- if (source) {
- source.cancel('abort')
- source = null
- }
- }
- // request interceptor
- service.interceptors.request.use(
- config => {
- // do something before request is sent
- if (store.getters.token) {
- config.headers['Authorization'] = `Bearer ${store.getters.token}`
- }
- if (!config.background) {
- config.cancelToken = getCancelToken()
- }
- return config
- },
- error => {
- console.log(error) // for debug
- // do something with request error
- return 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 => {
- const res = response.data || {}
- if (res.success) {
- return res
- }
- if (!response.config?.custom) {
- Message({
- type: 'error',
- message: res.errMessage || '请求异常'
- })
- }
- return Promise.reject(res)
- },
- error => {
- const isCancel = axios.isCancel(error)
- const { response, config } = error
- if (response) {
- const { status } = response
- if (status === 401) {
- // to re-login
- MessageBox.confirm(
- '登录状态已过期,请重新登录',
- '系统提示',
- {
- type: 'warning',
- confirmButtonText: '重新登录',
- center: true,
- showClose: false,
- showCancelButton: false,
- closeOnClickModal: false
- }
- ).then(() => {
- store.dispatch('user/resetToken').then(() => {
- location.reload()
- })
- })
- } else if (!config?.custom) {
- const { errMessage } = response.data
- Message({
- type: 'error',
- message: errMessage || '请求异常'
- })
- }
- return Promise.reject({ isCancel, ...response.data })
- }
- let { message } = error
- if (!config?.custom && !isCancel) {
- if (message) {
- if (/timeout/.test(message)) {
- message = '请求超时'
- }
- } else {
- message = '请求异常'
- }
- Message({
- type: 'error',
- message
- })
- }
- return Promise.reject({ errCode: -1, errMessage: message, isCancel })
- }
- )
- export default service
|