fetch.js add tips

This commit is contained in:
Pan 2017-05-16 09:59:04 +08:00
parent 69fe4d1e91
commit 88f2f7eadd
1 changed files with 37 additions and 18 deletions

View File

@ -1,17 +1,20 @@
import axios from 'axios'; import axios from 'axios';
import { Message } from 'element-ui'; import { Message } from 'element-ui';
import store from '../store'; import store from '../store';
import router from '../router'; // import router from '../router';
// 创建axios实例
const service = axios.create({ const service = axios.create({
baseURL: process.env.BASE_API baseURL: process.env.BASE_API, // api的base_url
timeout: 5000 // 请求超时时间
}); });
// request拦截器
service.interceptors.request.use(config => { service.interceptors.request.use(config => {
// Do something before request is sent // Do something before request is sent
if (store.state.token) { console.log(store.getters.token)
config.headers.Token = store.state.token; if (store.getters.token) {
config.headers['X-Token'] = store.getters.token; // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
} }
return config; return config;
}, error => { }, error => {
@ -20,22 +23,38 @@ service.interceptors.request.use(config => {
Promise.reject(error); Promise.reject(error);
}) })
// respone拦截器
service.interceptors.response.use( service.interceptors.response.use(
response => response, 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
// }
,
error => { error => {
console.log('err' + error);// for debug console.log('err' + error);// for debug
const code = error.response.data; Message({
if (code === 50008 || code === 50014 || code === 50012) { message: error.message,
Message({ type: 'error',
message: res.message, duration: 5 * 1000
type: 'error', });
duration: 5 * 1000
});
// 登出
store.dispatch('FedLogOut').then(() => {
router.push({ path: '/login' })
});
}
return Promise.reject(error); return Promise.reject(error);
} }
) )