/*
* @Description: 拦截器
* @Version: 1.0
* @Autor: Nanke_南柯
* @Date: 2020-09-04 09:07:31
* @LastEditors: Nanke_南柯
* @LastEditTime: 2020-10-21 16:24:27
*/
import axios from 'axios'
import {
Message
} from 'element-ui'
import qs from 'qs'
let timeout = 8000;
// 创建一个axios实例
const service = axios.create({
baseURL: process.env.VUE_APP_URL,
timeout: timeout,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
}
})
let mark = 'API_ONE';//区分请求哪一个域名
// 请求拦截器
service.interceptors.request.use(
config => {
if (config.requestBaseUrl === 'one') { // API 志豪
config.baseURL = process.env.VUE_APP_URL
mark = 'API_ONE'
}
if (config.requestBaseUrl === 'two') { // API 大屏
config.baseURL = process.env.VUE_APP_URL2
mark = 'API_TWO'
}
// 请求前
if (config.method === 'post') {
config.data = qs.stringify(config.data)
}
return config
},
error => {
// 做一些请求错误
return Promise.reject(error)
}
)
// 响应拦截器
service.interceptors.response.use(
/**
*通过自定义代码确定请求状态*/
response => {
const res = response.data
if (mark === 'API_ONE') {
if (res.code != 0) {
Message({
message: res.msg || '后台异常',
type: 'error',
duration: 5 * 1000
});
return Promise.reject(new Error(res.message || 'Error'))
} else {
return res
}
} else {
if (res.Code === "0") {
Message({
message: res.Msg || '后台异常',
type: 'error',
duration: 5 * 1000
});
return Promise.reject(new Error('Error'))
} else {
return res
}
}
},
error => {
const ISture = error.message.indexOf('500') == -1
if (ISture) {
Message({
message: `网络超时,请求时间大于${timeout / 1000}秒未成功响应,请刷新重试`,
type: 'error',
duration: 6 * 1000
});
} else {
Message({
message: '服务器返回:500错误',
type: 'error',
duration: 5000
})
}
return Promise.reject(error)
}
)
export default service