import axios from 'axios'; class HttpRequest { constructor(options) { this.options = options; this.queues = {}; } getInsideConfig() { const config = { baseURL: this.options.baseUrl, // baseURL timeout: 10000, responseType: 'json', withCredentials: false, // default headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json', Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest', ...this.options.headers, }, }; return config; } destroy(url) { delete this.queues[url]; } interceptors(instance, url, options) { // 请求拦截 instance.interceptors.request.use( config => { this.queues[url] = true; if (options.beforeRequest instanceof Function) { options.beforeRequest({ queues: this.queues, config, options }); } return config; }, error => Promise.reject(error), ); // 响应拦截 instance.interceptors.response.use( res => { // success this.destroy(url); const { data, status } = res; return { data, status }; }, error => { // error this.destroy(url); if (error.response) { console.log(error.response); } return Promise.reject(error); }, ); } request(options) { const instance = axios.create(); const ops = Object.assign(this.getInsideConfig(), options); this.interceptors(instance, ops.url, ops); return instance(ops); } } export default HttpRequest;