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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
| import axios from 'axios';
import { Message } from 'element-ui';
import routes from '../router';
class Http { constructor () { this.$msg = Message;
this.$axios = axios.create({ baseURL: 'https://example.com/api/', timeout: 10000 });
this.$axios.interceptors.request.use(config => { config.headers['Authorization'] = window.sessionStorage.getItem('token'); config.headers['Accept'] = 'application/json'; return config; }, error => { Promise.reject(error); });
this.$axios.interceptors.response.use(response => { if(response.status === 200) { if(response.data) { if(response.data.code === 1) { return Promise.resolve(response.data || true); }
this.$msg.error(response.data.message); return Promise.reject(response.data || true); }
return Promise.resolve(response || false); } else if(response.status === 401) { this.$msg.error('请登录');
routes.push({ name: 'login' }); }
return Promise.reject(response || false); }, (error) => { if (error.code === 'ECONNABORTED') { this.$msg.error('请求超时'); } else { switch (error.response.status) { case 401: this.$msg.closeAll(); this.$msg.error('请登录'); break;
case 429: this.$msg.error('请求频繁,稍候重试'); break;
default: console.log('请求错误', error, error.response); break; } }
return Promise.reject(error); }); }
get (url, params = {}) { if(params.hasOwnProperty('total')) { delete params['total']; }
return this.$axios.get(`${url}`, { params }); }
getPages (name, page = 1, params = {}) { return this.get(`${name}?page=${page}`, params); }
getFull (name) { return this.get(`${name}/all`); }
getShow (name, id) { return this.get(`${name}/${id}`); }
post (url, data = {}, config = {}) { return this.$axios.post(`${url}`, data, config); }
put (url, data = {}, config = {}) { return this.$axios.put(url, data, config); }
putUpdate (name, data) { if(!data.hasOwnProperty('id') || !data['id']) return false; return this.$axios.put(`${name}/${data['id']}`, data); }
delete (name, id) { const url = typeof id == 'undefined' ? name : `${name}/${id}`;
return this.$axios.delete(url); } }
export default new Http
|