fe-drone-ci/src/utils/fetch.js

63 lines
1.7 KiB
JavaScript
Raw Normal View History

2017-04-18 07:09:13 +00:00
import axios from 'axios';
import { Message } from 'element-ui';
import store from '../store';
2017-05-16 01:59:04 +00:00
// import router from '../router';
2017-04-18 07:09:13 +00:00
2017-05-16 01:59:04 +00:00
// 创建axios实例
2017-05-15 09:56:45 +00:00
const service = axios.create({
2017-05-16 01:59:04 +00:00
baseURL: process.env.BASE_API, // api的base_url
timeout: 5000 // 请求超时时间
2017-05-15 09:56:45 +00:00
});
2017-05-16 01:59:04 +00:00
// request拦截器
2017-05-15 09:56:45 +00:00
service.interceptors.request.use(config => {
// Do something before request is sent
2017-05-16 01:59:04 +00:00
console.log(store.getters.token)
if (store.getters.token) {
config.headers['X-Token'] = store.getters.token; // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
2017-05-15 09:56:45 +00:00
}
return config;
}, error => {
// Do something with request error
console.log(error); // for debug
Promise.reject(error);
})
2017-05-16 01:59:04 +00:00
// respone拦截器
2017-05-15 09:56:45 +00:00
service.interceptors.response.use(
2017-05-16 01:59:04 +00:00
response => response
/**
/**
* 下面的注释为通过response自定义code来标示请求状态当code返回如下情况为权限有问题登出并返回到登录页
* 如通过htmlrequest 状态码标示 逻辑可写在下面error中
*/
// const code = response.data.code;
// // 50014:Token 过期了 50012:其他客户端登录了 50008:非法的token
// if (code === 50008 || code === 50014 || code === 50012) {
// Message({
// message: res.message,
// type: 'error',
// duration: 5 * 1000
// });
// // 登出
// store.dispatch('FedLogOut').then(() => {
// router.push({ path: '/login' })
// });
// } else {
// return response
// }
,
2017-05-15 09:56:45 +00:00
error => {
console.log('err' + error);// for debug
2017-05-16 01:59:04 +00:00
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
});
2017-05-15 09:56:45 +00:00
return Promise.reject(error);
}
)
export default service;