思路
- 接收请求配置,包括url、method、params、data
- 返回Promise对象,让用户定义回调函数
- 处理params中的查询字符
- 新建XMLHttpRequest对象,发送请求报文
- 处理响应报文
代码
export function request ({
url,
method = 'GET',
params = {},
data = {}
}) {
return new Promise((resolve, reject) => {
let queryString = '';
Object.keys(params).forEach(key => {
queryString += `${key}=${params[key]}&`
});
if(queryString){
queryString = queryString.substring(0, queryString.length-1);
url = url + '?' + queryString;
}
const xhr = new XMLHttpRequest();
xhr.open(url, method);
if(method === 'GET' || method === 'DELETE'){
xhr.send();
} else if (method === 'POST' || method === 'PUT'){
xhr.setRequestHeader('Content-type', 'application/json;charset=utf-8');
xhr.send(JSON.stringify(data));
}
xhr.onreadystatechange = function () {
if(xhr.readyState !== 4) {
return;
}
if(xhr.status >= 200 && xhr.status <300){
const result = {
data: JSON.parse(xhr.response),
status: xhr.status,
statusText: xhr.statusText
}
resolve(result);
} else {
reject(new Error('request error status is ' + xhr.status));
}
}
});
}