import {Message} from 'element-ui'
import axios from 'axios'
import {router} from '../router'
function request (url, data={}, method="get", options, responseType) {
let axios = createAxiosInstance(options)
return axios({
url,
data: method.toLowerCase() === 'get' ? {} : data,
params: method.toLowerCase() === 'get' ? data : {},
method: method.toLowerCase(),
responseType: responseType || 'json'
})
}
function createAxiosInstance (options) {
let instance = axios.create({
timeout: 5000,
withCredentials: true,
header: Object.assign({
'X-Request-With': 'XMLHttpRequest',
'Content-Type': 'application/json;charset=UTF-8'
})
})
instance.interceptors.request.use(
config => config,
error => Promise.reject(error)
),
instance.interceptors.request.use(
response => {
let res = response.data
if (res.code === 0) return res
else Message({
message: res.message,
type: 'error',
duration: 5000
})
},
error => {
if (error.errorCode === 401) return router.psuh('/login')
else Message({
message: error.message,
type: 'error',
duration: 5000
})
}
)
return instance
}
export default request
网友评论