From 88f2f7eadd5a615da95abe64010c310786f9540f Mon Sep 17 00:00:00 2001 From: Pan Date: Tue, 16 May 2017 09:59:04 +0800 Subject: [PATCH] fetch.js add tips --- src/utils/fetch.js | 55 +++++++++++++++++++++++++++++++--------------- 1 file changed, 37 insertions(+), 18 deletions(-) diff --git a/src/utils/fetch.js b/src/utils/fetch.js index f72817ad..1b917a1a 100644 --- a/src/utils/fetch.js +++ b/src/utils/fetch.js @@ -1,17 +1,20 @@ import axios from 'axios'; import { Message } from 'element-ui'; import store from '../store'; -import router from '../router'; - +// import router from '../router'; +// 创建axios实例 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 => { // Do something before request is sent - if (store.state.token) { - config.headers.Token = store.state.token; + console.log(store.getters.token) + if (store.getters.token) { + config.headers['X-Token'] = store.getters.token; // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改 } return config; }, error => { @@ -20,22 +23,38 @@ service.interceptors.request.use(config => { Promise.reject(error); }) +// respone拦截器 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 => { console.log('err' + error);// for debug - const code = error.response.data; - if (code === 50008 || code === 50014 || code === 50012) { - Message({ - message: res.message, - type: 'error', - duration: 5 * 1000 - }); - // 登出 - store.dispatch('FedLogOut').then(() => { - router.push({ path: '/login' }) - }); - } + Message({ + message: error.message, + type: 'error', + duration: 5 * 1000 + }); return Promise.reject(error); } )