import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getParams } from '@/utils/index'
// 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 => {
// do something before request is sent
const token = getToken()
// 判断是否cookie存在token
if (token) {
config.headers['token'] = token
} else {
const query = getParams()
const queryToken = query.token ? query.token : '';
config.headers['token'] = queryToken
setToken(queryToken)
}
const params = config.params
const data = config.data
// 把params里空的参数去除
params ? deleteEmptyItem(params) : ''
// 把data里空的参数去除
data ? deleteEmptyItem(data) : ''
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
*/
response => {
let res = response.data
// 如果是返回的文件
if (response.config.responseType == 'blob') {
return res
}
// 兼容服务端返回的字符串数据
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
// if the custom code is not 0
if (res.code !== 0) {
if (res.code === 401) { // 401未登录
errorMsg(res.msg || '未登录或者登陆状态已失效')
// to re-login
removeToken();
// 方便我们本地调试,去修改URL的token
location.href.indexOf('local') === -1 && (location.href = process.env.VUE_APP_LOGIN_URL)
} else if (res.code === 500) { // 500 服务器异常
errorMsg(res.msg || '服务器异常')
} else if (res.code === 406) { // 406 没有权限
errorMsg(res.msg || '您没有权限')
} else {
errorMsg(res.msg || '服务器异常')
}
return Promise.reject(res.message || 'error')
} else {
return res
}
},
error => {
console.log('err' + error) // for debug
errorMsg(error.message)
return Promise.reject(error)
}
)
/**
* 弹出错误提醒
* @param {String} msg 消息
*/
function errorMsg(msg) {
Message({
message: msg,
type: 'error',
duration: 3 * 1000
})
}
/**
* 清空对象为空的属性
* @param {Object} obj 处理对象
*/
function deleteEmptyItem(obj) {
for(let i in obj) {
(obj[i] === '' || obj[i] === undefined || obj[i] === null) ? delete obj[i] : ''
}
}
export default service
网友评论