直接上代码
import axios from 'axios';
import { MessageBox, Message } from 'element-ui';
import store from '@/store';
import router from '@/router';
import { setToken, getToken, removeToken } from "@/utils/cookies";
const service = axios.create({
baseURL: store.state.baseDomain,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
})
service.interceptors.request.use(
config => {
let token = getToken();
if (token != undefined && token != '') {
config.headers['Authorization'] = 'Bearer ' + token;
}
return config
},
error => {
return Promise.reject(error)
}
)
service.interceptors.response.use(
response => {
const res = response.data
if (res.__abp) {
return handleResponse(response)
}
if (response.status !== 200) {
Message({
message: res.message || 'Error',
type: 'error',
duration: 5 * 1000
})
if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
confirmButtonText: 'Re-Login',
cancelButtonText: 'Cancel',
type: 'warning'
}).then(() => {
store.dispatch('resetToken').then(() => {
location.reload()
})
})
}
return Promise.reject(new Error(res.message || 'Error'))
} else {
return res
}
},
error => {
if (error.response.data.__abp) {
return handleResponse(error.response)
}
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
function handleResponse(response) {
var originalData = response.data
if (originalData.success === true) {
response.data = originalData.result
return response
} else if (originalData.success === false) {
if (response.status == 401 && response.config.abpHandleError !== false) {
store.dispatch('resetToken').then(_ => {
router.push(`/login?redirect=${location.hash.replace('#', '')}${location.search}`).catch(() => { })
})
originalData.error.message = '为了您的帐号安全,请重新登录';
}
if (originalData.error) {
if (response.config.abpHandleError !== false) {
Message.error(originalData.error.message || '请求出错了!!!')
}
} else {
originalData.error = defaultError
}
response.data = originalData.error
return Promise.reject(response)
} else {
return Promise.reject(response)
}
}
window.request = service;
export default service
|