Skip to content

Commit 88f2f7e

Browse files
committed
fetch.js add tips
1 parent 69fe4d1 commit 88f2f7e

File tree

1 file changed

+37
-18
lines changed

1 file changed

+37
-18
lines changed

src/utils/fetch.js

Lines changed: 37 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,20 @@
11
import axios from 'axios';
22
import { Message } from 'element-ui';
33
import store from '../store';
4-
import router from '../router';
5-
4+
// import router from '../router';
65

6+
// 创建axios实例
77
const service = axios.create({
8-
baseURL: process.env.BASE_API
8+
baseURL: process.env.BASE_API, // api的base_url
9+
timeout: 5000 // 请求超时时间
910
});
1011

12+
// request拦截器
1113
service.interceptors.request.use(config => {
1214
// Do something before request is sent
13-
if (store.state.token) {
14-
config.headers.Token = store.state.token;
15+
console.log(store.getters.token)
16+
if (store.getters.token) {
17+
config.headers['X-Token'] = store.getters.token; // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
1518
}
1619
return config;
1720
}, error => {
@@ -20,22 +23,38 @@ service.interceptors.request.use(config => {
2023
Promise.reject(error);
2124
})
2225

26+
// respone拦截器
2327
service.interceptors.response.use(
24-
response => response,
28+
response => response
29+
30+
/**
31+
/**
32+
* 下面的注释为通过response自定义code来标示请求状态,当code返回如下情况为权限有问题,登出并返回到登录页
33+
* 如通过htmlrequest 状态码标示 逻辑可写在下面error中
34+
*/
35+
// const code = response.data.code;
36+
// // 50014:Token 过期了 50012:其他客户端登录了 50008:非法的token
37+
// if (code === 50008 || code === 50014 || code === 50012) {
38+
// Message({
39+
// message: res.message,
40+
// type: 'error',
41+
// duration: 5 * 1000
42+
// });
43+
// // 登出
44+
// store.dispatch('FedLogOut').then(() => {
45+
// router.push({ path: '/login' })
46+
// });
47+
// } else {
48+
// return response
49+
// }
50+
,
2551
error => {
2652
console.log('err' + error);// for debug
27-
const code = error.response.data;
28-
if (code === 50008 || code === 50014 || code === 50012) {
29-
Message({
30-
message: res.message,
31-
type: 'error',
32-
duration: 5 * 1000
33-
});
34-
// 登出
35-
store.dispatch('FedLogOut').then(() => {
36-
router.push({ path: '/login' })
37-
});
38-
}
53+
Message({
54+
message: error.message,
55+
type: 'error',
56+
duration: 5 * 1000
57+
});
3958
return Promise.reject(error);
4059
}
4160
)

0 commit comments

Comments
 (0)