import axios from 'axios'
|
import CryptoJS from 'crypto-js';
|
import apiConfig from '@/config/baseurl'
|
import store from '@/store'
|
|
import {
|
Message
|
} from 'element-ui'
|
|
|
const service = axios.create({
|
baseURL: apiConfig.baseURL,
|
withCredentials: false, // 当跨域请求时发送cookie
|
timeout: 30000, // request timeout
|
})
|
|
// 请求拦截
|
service.interceptors.request.use(
|
config => {
|
const env = process.env.NODE_ENV; //development production
|
let { url } = config;
|
if (env === 'production') {
|
url = url.replace(/.$/, '0');
|
config.url = url;
|
} else {
|
url = url.replace(/.$/, '1');
|
config.url = url;
|
}
|
|
const nowTime = Date.now()
|
const sign = CryptoJS.HmacSHA1(nowTime, apiConfig.secretKEY).toString(CryptoJS.enc.Base64)
|
|
config['headers']['timestamp'] = nowTime
|
config['headers']['sign'] = sign
|
if (config.method == 'get') {
|
if (!config.params) config.params = {};
|
config.params = {
|
...config.params,
|
}
|
}
|
if (config.method == 'post') {
|
if (!config.data) config.data = {};
|
config.data = {
|
...config.data,
|
}
|
}
|
return config
|
},
|
error => {
|
return Promise.reject(error)
|
}
|
)
|
|
// 响应拦截
|
service.interceptors.response.use(
|
response => {
|
if (!response) {
|
return
|
}
|
const res = response;
|
if (res.data.status == 0) {
|
if (!res.data) {
|
return Promise.resolve({})
|
}
|
return Promise.resolve(res.data)
|
} else {
|
if (res.data.status == 103 || res.data.status == 401) {
|
Message({
|
message: res.data.msg || '登录已过期,请重新登录',
|
type: 'warning',
|
duration: 2000
|
})
|
store.commit('SET_USERINFO', {})
|
store.commit('SET_USERNAME', '')
|
localStorage.clear()
|
window.location.replace('/');
|
return Promise.reject(res.data)
|
}
|
Message({
|
message: res.data.msg || '服务器错误',
|
type: 'error',
|
duration: 2000
|
})
|
return Promise.reject(res.data)
|
}
|
},
|
error => {
|
return Promise.reject(error.message)
|
}
|
)
|
export default service
|