2018-07-16 22:22:55 +08:00
|
|
|
import axios from 'axios'
|
2018-08-24 17:05:32 +08:00
|
|
|
import { Message } from 'element-ui'
|
|
|
|
|
import util from '@/libs/util'
|
2018-07-16 22:22:55 +08:00
|
|
|
|
2018-08-26 22:07:26 +08:00
|
|
|
// 创建一个 axios 实例
|
2018-08-24 17:05:32 +08:00
|
|
|
const service = axios.create({
|
|
|
|
|
baseURL: process.env.VUE_APP_API,
|
|
|
|
|
timeout: 5000 // 请求超时时间
|
2018-07-17 16:38:59 +08:00
|
|
|
})
|
2018-07-16 22:22:55 +08:00
|
|
|
|
2018-08-26 22:07:26 +08:00
|
|
|
// 请求拦截器
|
2018-08-24 17:05:32 +08:00
|
|
|
service.interceptors.request.use(
|
|
|
|
|
config => {
|
2018-08-26 22:07:26 +08:00
|
|
|
// 在请求发送之前做一些处理
|
2018-08-26 10:28:26 +08:00
|
|
|
if (!(/^https:\/\/|http:\/\//.test(config.url))) {
|
|
|
|
|
const token = util.cookies.get('token')
|
|
|
|
|
if (token && token !== 'undefined') {
|
|
|
|
|
// 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
|
|
|
|
|
config.headers['X-Token'] = token
|
|
|
|
|
}
|
2018-08-24 17:05:32 +08:00
|
|
|
}
|
|
|
|
|
return config
|
|
|
|
|
},
|
|
|
|
|
error => {
|
2018-08-26 22:07:26 +08:00
|
|
|
// 发送失败
|
|
|
|
|
console.log(error)
|
2018-08-24 17:05:32 +08:00
|
|
|
Promise.reject(error)
|
2018-08-22 10:24:02 +08:00
|
|
|
}
|
2018-08-24 17:05:32 +08:00
|
|
|
)
|
|
|
|
|
|
2018-08-26 22:07:26 +08:00
|
|
|
// 响应拦截器
|
2018-08-24 17:05:32 +08:00
|
|
|
service.interceptors.response.use(
|
|
|
|
|
response => {
|
2018-08-27 09:10:30 +08:00
|
|
|
// dataAxios 是 axios 返回数据中的 data
|
|
|
|
|
const dataAxios = response.data
|
|
|
|
|
// 这个状态码是和后端约定的
|
|
|
|
|
const { code } = dataAxios
|
|
|
|
|
// 根据 code 进行判断
|
|
|
|
|
if (code === undefined) {
|
|
|
|
|
// 如果没有 code 代表这不是后端返回的数据(例如请求 D2Admin 最新版本)
|
|
|
|
|
return dataAxios
|
|
|
|
|
} else {
|
|
|
|
|
// 有 code 代表这是一个后端接口
|
|
|
|
|
return dataAxios.data
|
|
|
|
|
}
|
2018-08-24 17:05:32 +08:00
|
|
|
},
|
|
|
|
|
error => {
|
2018-08-26 22:16:53 +08:00
|
|
|
util.log.danger('>>>>>> Error >>>>>>')
|
2018-08-26 22:07:26 +08:00
|
|
|
console.log(error)
|
2018-08-24 17:05:32 +08:00
|
|
|
Message({
|
|
|
|
|
message: error.message,
|
|
|
|
|
type: 'error',
|
|
|
|
|
duration: 5 * 1000
|
|
|
|
|
})
|
|
|
|
|
return Promise.reject(error)
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
export default service
|