vue请求拦截统一给所有请求加loading
import axios from 'axios'
import { Toast, Dialog } from 'vant'
import router from '@/router'
import { Tips } from '@/utils/index'
import configs from "@/config";
// create an axios instance
const service = axios.create({
baseURL: configs.HTTP_URL,
withCredentials: true, // send cookies when cross-domain requests
timeout: 50000 // 等待时间
})
console.log(configs)
// request拦截器 request interceptor
service.interceptors.request.use(
config => {
// 不传递默认开启loading
if (!config.hideloading) {
// loading
Tips.loading(config.message)
}
if (localStorage.getItem('gy_h5_access_token')) {
config.headers['access_token'] = localStorage.getItem('gy_h5_access_token')
}
config.headers['x-service-id'] = '123'
return config
},
error => {
// do something with request error
console.log(error) // for debug
return Promise.reject(error)
}
)
// respone拦截器
service.interceptors.response.use(
response => {
Toast.clear()
const res = response.data
if (res.status && res.status !== 200) {
Tips.error(res.msg)
return Promise.reject(res || 'error')
} else {
if (res.code === 200) {
return Promise.resolve(res.data)
} else {
Tips.error(res.msg)
return Promise.reject(res || 'error')
}
}
},
error => {
Toast.clear()
if (error.response.status === 401) {
Dialog({ message: '登录过期,请重新登录' }).then(() => {
localStorage.removeItem('gy_h5_access_token')
if (configs.otherUrl.ifsUrl) {
window.location.href = configs.otherUrl.ifsUrl + '/login'
} else {
router.replace({ name: 'NotFound' })
}
})
} else {
console.log(error,'error')
Tips.error(error.response.data.message)
}
return Promise.reject(error)
}
)
export default service