实现axios的二次封装

import {
	baseURL
} from './config.js';
/*
*封装请求前后loading的开启和关闭
* 请求拦截和响应拦截
* 取消请求 (订阅发布的模式);
*/

// import axios from 'axios';
//每请求一次创建一个唯一的axios
class AjaxFetch {
	constructor() {
		this.config = {
			timeout: 3000,
			withCredentials: true,
			responseType: 'json',
			baseURL: baseURL,
		};
		this.queue = {}; //收集请求的队列
	
		this.id=1;
	};
	request(option) {
		//创建一个axios实例
		this.config = { 
			...this.config,
			...option
		};
		let instance = axios.create();
		this.interceptors(instance);
		return instance(this.config);
	};
	interceptors(instance) {
		instance.interceptors.request.use(function(config) {
			config.cancelToken = new cancelToken((c)=>{
				// 这里的axios标识我是用请求地址&请求方式拼接的字符串,当然你可以选择其他的一些方式
				//c是一个函数   
				store.commit('push_cancel',{fn:c,url:config.url});			//存放取消的函数实例
				//store.commit('push_cancel',{fn:this.cache[this.id],id:this.id});
			});
	
// 			let CancelToken = instance.CancelToken;
// 			let source = CancelToken.source();
//			store.commit('push_cancel',{source,config.url});			//存放取消的函数实例
			//获取每个请求取消对象
			config.cancelToken = source.token;
			// 在发送请求之前做些什么
			if (Object.keys(this.queue).length === 0) {
				console.log('...开启loading')
			}
			this.queue[this.config.url] = this.config.url;
			return config;
		}, function(error) {
			// 对请求错误做些什么
			return Promise.reject(error);
		});
		// 添加响应拦截器
		instance.interceptors.response.use(function(response) {
			//响应完成时,将已经完成的请求从数组中移除  其他想取消请求也要手动commit一下
			store.commit('clear_cancel',{url:this.config.url});
			// 对响应数据做点什么
			delete this.queue[this.config.url];
			if (Object.keys(this.queue).length === 0) {
				console.log('...关闭loading');
			}
			//接口数据统一处理
			if (response.data.code === 200) {
				return Promise.resolve(response.data);
			} else {
				return Promise.reject();
			}
		}, function(error) {
			// 对响应错误做点什么
			delete this.queue[this.config.url];
			if (Object.keys(this.queue).length === 0) {
				console.log('...关闭loading');
			}
			if (instance.isCancel(error)) {
				console.log('Request canceled', thrown.message);		//取消请求信息
			} else {
				// 处理错误
				console.log('错误信息')
			}
			return Promise.reject(error);
		});
	}

}
export default new AjaxFetch();

猜你喜欢

转载自blog.csdn.net/Miss_hhl/article/details/104797273