原生AJAX请求封装

116 阅读1分钟
let httpClient = {};
const TimeOut = 15 * 1000;
function send(body) {
	loading.showLoading()
	return new Promise((resolve, reject) => {
		let xhr = new XMLHttpRequest()
		xhr.open(body.method, body.url);
		xhr.setRequestHeader("Content-Type", body.contentType)
		xhr.timeout = TimeOut;
		xhr.onreadystatechange = function(resp) {
			loading.hideLoading()
			respone(resolve, reject, resp)
		}
		xhr.send(body.data)
	})
}


function respone(resolve, reject, resp) {
	resp = resp.target;
	if (resp.status === 200) {
		if (resp.readyState === 4) {
			resolve(resp.response)
		}
	} else {
		reject(resp)
	}
}

httpClient.get = async function(url) {
	let body = {
		url: url,
		method: "GET",
	}
	return await send(body)
}

httpClient.post = async function(url, data) {
	let body = {
		url: url,
		method: "POST",
		data: JSON.stringify(data),
		contentType: "application/json"
	}
	
	return await send(body)
}

export default httpClient