import axios from 'axios'; import { string } from 'prop-types'; class HttpRequest { constructor(options) { this.options = options; this.queues = {}; } getInsideConfig() { let headers = {}; if (this.options.headers instanceof Function) { headers = this.options.headers(); } else { headers = { ...this.options.headers }; } 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', ...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); if (options.successHandler instanceof Function) { options.successHandler({ queues: this.queues, res, options }); } const { data, status } = res; return { data, status }; }, error => { // error this.destroy(url); if (options.errorHandler instanceof Function) { options.errorHandler({ queues: this.queues, error, options }); } 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;