直接看代码。可以进行请求拦截,返回数据拦截,并不是用promise进行封装的,因为需要使用到上传进度,所以是简单的回调方式封装的。
class XMLHttp{
constructor({
timeOut=13000000,
baseUrl='',
}={}){
this.timeOut = timeOut;
this.baseUrl = baseUrl;
this.intercept = {
request:{
success:undefined,
error:undefined,
},
response:{
success:undefined,
error:undefined,
},
};
}
createRequest({
method,url,params,responseType,async=true,withCredentials=false,
readyStateChange,
loadStart,
progress,
abort,
error,
load,
timeOut,
loadend,
}){
try{
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = ()=>{
readyStateChange && readyStateChange(xhr);
};
xhr.upload.addEventListener("progress", (evt)=>{
progress && progress(evt);
});
xhr.addEventListener("load", ()=>{
load && load(xhr);
});
xhr.addEventListener("error", ()=>{
error && error(xhr);
});
xhr.addEventListener("abort", ()=>{
abort && abort(xhr);
});
xhr.addEventListener("loadstart", ()=>{
loadStart && loadStart(xhr);
});
xhr.addEventListener("loadend", ()=>{
loadend && loadend(xhr);
});
if(async){
xhr.timeout = this.timeOut;
xhr.addEventListener("timeout", ()=>{
timeOut && timeOut(xhr);
});
xhr.responseType = responseType || 'text';
}
xhr.withCredentials = withCredentials;
xhr.open(
method ? method.toUpperCase() : 'GET',
this.baseUrl + url,
async,
);
this.intercept.request.success && this.intercept.request.success(xhr);
xhr.send(params);
return xhr;
}catch(e){
this.intercept.request.error && this.intercept.request.error(e);
}
}
setRequestIntercept(success,error){
this.intercept.request.success = success;
this.intercept.request.error = error;
}
setResponseIntercept(success,error){
this.intercept.response.success = success;
this.intercept.response.error = error;
}
requestMode({ //请求方式
url='',params={},async,withCredentials,method,
onSuccess=()=>{},
error=()=>{},
progress=()=>{},
loadend=()=>{},
}={}){
return this.createRequest({
url,
params,
async,
withCredentials,
method,
progress,
loadend,
readyStateChange:(xhr)=>{
if(xhr.readyState !== 4) return;
if(xhr.status === 200) {
this.intercept.response.success?
this.intercept.response.success(
xhr,
{
onSuccess,
error,
},
):
onSuccess(xhr);
} else {
this.intercept.response.error?
this.intercept.response.error(
xhr,
{
onSuccess,
error,
},
):
error(xhr);
}
},
});
}
get(option){
return this.requestMode({
...option,
method:'get',
});
}
post(option){
return this.requestMode({
...option,
method:'post',
});
}
put(option){
return this.requestMode({
...option,
method:'put',
});
}
delete(option){
return this.requestMode({
...option,
method:'delete',
});
}
}
官方XMLHttpRequest文档