Vue 封装 axios.js ,模块化请求 API 为 model.js
Axios.js
| 12
 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,
 });
 
 
 
 
 console.log(process.env);
 instance.interceptors.request.use(
 config => {
 
 console.log(config.url, process.env.NODE_ENV);
 if (config.method === 'post') {
 config.data = qs.stringify(config.data);
 }
 console.log('******loading********start');
 
 return config;
 },
 error => {
 return Promise.reject(error);
 },
 );
 
 instance.interceptors.response.use(
 response => {
 
 
 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
| 12
 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 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;
 
 |