Vue 封装 axios.js ,模块化请求 API 为 model.js

Axios.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import axios from 'axios';
import qs from 'qs';
import router from '../common/Router';
import Toast from 'vant/lib/toast';
import 'vant/lib/toast/style';
//接口配置
var instance = axios.create({
baseURL: process.env.NODE_ENV == 'development' ? '/api' : window.ApiUrl,
});

//////////////////////////
// let elementLoading;
//添加请求拦截器
console.log(process.env);
instance.interceptors.request.use(
config => {
//在一个ajax发送前执行操作 config.url config.method
console.log(config.url, process.env.NODE_ENV);
if (config.method === 'post') {
config.data = qs.stringify(config.data);
}
console.log('******loading********start');
// elementLoading=Loading.service({ fullscreen: true ,background:'rgba(255, 255, 255, 0.5)'});//
return config;
},
error => {
return Promise.reject(error);
},
);
//添加响应拦截器
instance.interceptors.response.use(
response => {
//在一个ajax响应后再执操作
// elementLoading.close();
console.log('******loading********end');
console.log(response);
if (response.data.code != 1) {
if (response && response.data) {
Toast(response.data.data || response.data.msg);
}
router.push('/login');
}
if (response && response.data && response.data.data) {
try {
response.data.data = JSON.parse(response.data.data);
} catch (error) {
console.log(error);
}
}
return response;
},
error => {
if (instance.isCancel(error)) {
console.warn('isCancel->', error.message);
} else {
console.log('error', error);
}
return Promise.reject(error);
},
);
export default instance;

Model.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import router from './Router';
import axios from './Axios';
// import Dialog from 'vant/lib/dialog';
// import 'vant/lib/dialog/style';
import Toast from 'vant/lib/toast';
import 'vant/lib/toast/style';
const model = {
Login(json, callback) {
const getResponse = ({ data }) => {
console.log('model Login', data);
if (data.code == 1) {
Toast('登录成功');
localStorage.setItem('token', data.data.token);
router.push({ path: '/load' });
} else {
console.log('Login error');
}
callback && callback(data);
};
axios.post('/login', json).then(getResponse);
},
};

export default model;

编辑文章✏