aiccs/src/utils/request.js

95 lines
2.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getSsoToken, getToken } from '@/utils/auth'
// create an axios instance
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API // url = base url + request url
// withCredentials: true, // send cookies when cross-domain requests
// timeout: 5000 // request timeout
})
// request interceptor
service.interceptors.request.use(
config => {
if (getToken()) {
// 携带token
config.headers[process.env.VUE_APP_TOKEN_KEY] = getToken()
}
if (getSsoToken()) {
// 携带token
config.headers.ssoToken = getSsoToken()
}
return config
},
error => {
// do something with request error
console.log(error) // for debug
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
* 开发环境使用mock.js并不能模拟http状态码下面暂时使用业务的状态码
*/
response => {
const { status, data } = response
if (status === 401 || status === 403) {
// 没有登录或者没有权限
store.dispatch('user/resetToken').then(() => {
location.reload()
})
}
if (data.code && data.code !== 0) {
Message({
message: data.code === 3002 ? data.data.message : data.msg || '业务异常',
type: 'error',
duration: 5 * 1000
})
}
if (response.config.useResponseData) {
if (data.code !== 0) {
throw new Error(data.data?.message || data.msg)
}
return data.data
}
return response.config.useHeader ? response : data
},
error => {
console.error(error) // for debug
if (error.response.status === 401 || error.response.status === 403) {
Message({
message: error.response.data.msg || '没有权限访问',
type: 'error',
duration: 5 * 1000
})
// 没有登录或者没有权限
store.dispatch('user/resetToken').then(() => {
location.reload()
})
} else {
if (error.config.throwError || error.config.useResponseData) { // 不被拦截处理
throw error.response
} else {
Message({
message: error.response.data.msg || '请求失败,服务器开小差了',
type: 'error'
})
return error.response.data
}
}
}
)
export default service