在main.js入口文件里:
// 安裝VueAxios,讓全局Vue含有this.$HTTP請求方法
import { VueAxios } from './utils/request.js'
Vue.use(VueAxios)
request.js文件:
- axios.interceptors.request.use(config=>{},err=>{})
- service.interceptors.response.use(response=>{}, err=>{})
import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import notification from 'ant-design-vue/es/notification'
import { ACCESS_TOKEN } from '@/store/mutation-types'
const baseURL = 'http://192.168.0.192:8080/api'
// 創(chuàng)建 axios 實例
const service = axios.create({
baseURL: baseURL, // api base_url
timeout: 6000 // 請求超時時間
})
const err = (error) => {
if (error.response) {
const data = error.response.data
const token = Vue.ls.get(ACCESS_TOKEN)
if (error.response.status === 403) {
notification.error({
message: 'Forbidden',
description: data.message
})
}
if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
notification.error({
message: 'Unauthorized',
description: 'Authorization verification failed'
})
if (token) {
store.dispatch('Logout').then(() => {
setTimeout(() => {
window.location.reload()
}, 1500)
})
}
}
}
return Promise.reject(error)
}
// request interceptor
service.interceptors.request.use(config => {
const token = Vue.ls.get(ACCESS_TOKEN)
if (token) {
config.headers['Access-Token'] = token // 讓每個請求攜帶自定義 token 請根據(jù)實際情況自行修改
}
return config
}, err)
// response interceptor
service.interceptors.response.use((response) => {
return response.data
}, err)
const installer = {
vm: {},
install: (Vue) => {
if (this.installed) {
return
}
Object.defineProperties(Vue.prototype, {
$http: {
get: function get () {
return service
}
}
})
this.installed = true
}
}
export {
installer as VueAxios
}