Fetch请求器的封装

const baseUrl = 'url跟地址'

//参数转换
const queryString = params => '?' + Object
	.keys(params)
	.map(key => `${key}=${encodeURIComponent(params[key])}`)
	.join('&');

const request = (partialUrl, body, query, method = 'GET', mode = 'cors', contentType = 'application/x-www-form-urlencoded') => {
	const needContentType = ['POST', 'PUT', 'GET'].includes(method.toUpperCase());
	const url = baseUrl + partialUrl + (query ? queryString(query) : '');
	return new Promise((success, fail) => fetch(url, {
		method, //请求方式
		mode,   //跨域模式
		data: body, //请求参数
		headers: {  //请求头
			...needContentType ? {
				'Content-Type': contentType
			} : {}
		}
	}).then(response => {
		success(response.json());
		fail(response);
	}))
}

class Fetch {
	constructor(before, after) {
		this.before = before; //请求前拦截器
		this.after = after; //请求后拦截器
	}

	_request(partialUrl, body, query, method, mode, contentType) {
		this.before && this.before();	// 执行请求前拦截器。
		const promise = request(partialUrl, body, query, method, mode, contentType);
		promise.finally(() => this.after && this.after()); // 执行请求后拦截器。
		return promise;
	}

	get(partialUrl, query, contentType) {

		return this._request(partialUrl, undefined, query, "GET", undefined, contentType);
	}

	delete(partialUrl, query) {
		return this._request(partialUrl, undefined, query, undefined, 'DELETE');
	}

	post(partialUrl, body, query, contentType) {
		return this._request(partialUrl, body, query, 'POST', undefined, contentType)
	}

	put(partialUrl, body, query, contentType) {
		return this._request(partialUrl, body, query, 'PUT', undefined, contentType)
	}

}

const FetchApi = {
	get: (partialUrl, query, contentType) => {
		return new Fetch().get(partialUrl, undefined, query, contentType);
	},
	delete: (partialUrl, query) => {
		return new Fetch().delete(partialUrl, undefined, query);
	},
	post: (partialUrl, body, query, contentType) => {
		return new Fetch().post(partialUrl, body, query, contentType);
	},
	put: (partialUrl, body, query, contentType) => {
		return new Fetch().put(partialUrl, body, query, contentType);
	}
}

export default FetchApi;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值