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
| import axios from 'axios' import store from '@/store' import {Spin} from 'view-design' const addErrorLog = errorInfo => { const {statusText, status, request: {responseURL}} = errorInfo let info = { type: 'ajax', code: status, mes: statusText, url: responseURL } if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info) }
class HttpRequest { constructor (baseUrl = baseURL) { this.baseUrl = baseUrl this.queue = [] } getInsideConfig () { const config = { baseURL: this.baseUrl, headers: {} } return config } destroy (url) { this.queue.pop() setTimeout(() => { if (!this.queue.length) { Spin.hide() } }, 100) } interceptors (instance, url) { instance.interceptors.request.use(config => { this.queue.push(url) if (this.queue.length) { Spin.show({ render: h => { return h('div', [ h('Icon', { 'class': 'spin-icon-load', props: { type: 'ios-loading', size: 30 } }), h('div', '加载中...') ]) } }) } return config }, error => { return Promise.reject(error) }) instance.interceptors.response.use(res => { this.destroy(url) const {data, status} = res return {data, status} }, error => { this.destroy(url) let errorInfo = error.response if (!errorInfo) { const {request: {statusText, status}, config} = JSON.parse(JSON.stringify(error)) errorInfo = { statusText, status, request: {responseURL: config.url} } } addErrorLog(errorInfo) return Promise.reject(error) }) } request (options) { const instance = axios.create() options = Object.assign(this.getInsideConfig(), options) this.interceptors(instance, options.url) return instance(options) } } export default HttpRequest
|