encodeURIComponent实现了对一些特殊字符的编码,传到后台需后台解码,可以根据自己的业务只对一些特殊的接口做编码。
post请求头Content-Type一般有json和form两种格式,分别以json和键值对格式传给后端。
function axios({
url,
method = 'GET',
params,
data = {},
header,
success,
fail,
}) {
return new Promise((resolve, reject) => {
method = method.toUpperCase()
let xhr = new XMLHttpRequest();
// params拼接到url后面
if (params) {
url += "?" + parameter(params);
}
xhr.open(method, url, true);
// 设置请求头
if (header) {
for (const key in header) {
if (key) {
xhr.setRequestHeader(key, header[key]);
}
}
}
if (method == "POST") {
// post有form和json两种格式,根据自己的需要选择,或者不写在header中配置
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// xhr.setRequestHeader("Content-Type", "application/json");
if (data) {
xhr.send(parameter(data));
// xhr.send(JSON.stringify(data));
} else {
xhr.send();
}
} else {
xhr.send(null);
}
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return
let {
status,
statusText,
} = xhr
// status[200,300)直接代表成功
if (status >= 200 && status < 300) {
let response = {
data: JSON.parse(xhr.response),
status,
statusText,
}
if (success) success(response)
resolve(response)
} else {
let error = new Error("响应出错,状态为:" + status + ",出错原因" + statusText)
if (fail) fail(error)
reject(error)
}
}
})
}
function parameter(obj) {
var arr = [];
for (var item in obj) {
arr.push(item + "=" + encodeURIComponent(obj[item]));
}
return arr.join("&");
}
// 测试
axios({
url: 'http://129.28.151.93/api/blog/list',
header: {
token: '5e3fd7109ce3d27781b07b92'
}
}).then(res => {
console.log(res);
})