カプセル化
export function axios({
method, url, params, data }) {
// 方法可大写可小写
method = method.toUpperCase();
// 返回值
return new Promise((resolve, reject) => {
// 1.创建对象
const xhr = new XMLHttpRequest();
// 2.初始化
let str = "";
for (const k in params) {
str += `${
k}=${
params[k]}&`;
}
str = str.slice(0, -1);
xhr.open(method, url + "?" + str);
// 3.发送请求
if (method === "POST" || method === "PUT" || method === "DELETE") {
// Content-type mime类型设置
// 请求头
xhr.setRequestHeader("Content-type", "application/json");
// 请求体
xhr.send(JSON.stringify(data));
} else {
// 如果是get方法
xhr.send();
}
// 设置响应结果的类型为json
xhr.responseType = "json";
// 4.处理结果
xhr.onreadystatechange = function () {
//
if (xhr.readyState === 4) {
// 判断响应状态码
if (xhr.status >= 200 && xhr.status <= 300) {
// 成功的状态
resolve({
// 成功的状态码
status: xhr.status,
// 成功的字符串,响应字符串
message: xhr.statusText,
// 响应体
body: xhr.response,
});
} else {
reject(new Error("请求失败,失败的状态码为" + xhr.status));
}
}
};
});
}
axios.get = function (url, options) {
// 发送AJAX请求 GET
return axios(Object.assign(options, {
method: "GET", url }));
};
axios.post = function (url, options) {
// 发送AJAX请求 POST
return axios(Object.assign(options, {
method: "POST", url }));
};
axios.put = function (url, options) {
// 发送AJAX请求 PUT
return axios(Object.assign(options, {
method: "PUT", url }));
};
axios.delete = function (url, options) {
// 发送AJAX请求 DELETE
return axios(Object.assign(options, {
method: "DELETE", url }));
};
使用
<script>
// 函数
// axios({
// // 请求类型
// method:'POST',
// // 请求url
// url:"",
// // 请求参数
// params:{
// a:100,
// b:200
// },
// // 请求体
// data:{
// c:300,
// d:400
// }
// }).then(response => {
// console.log(response);
// }).catch(r=>{
// console.log(r);
// })
// 调用对象
axios.get('',{
params:{
a:100,
b:100
}
}).then(response => {
console.log(response);
})
axios.post('',{
params:{
a:100,
b:100
},
data:{
c:300,
d:400
}
}).then(response => {
console.log(response);
})
// axios.put('',{
// params:{
// a:100,
// b:100
// }
// }).then(response => {
// console.log(response);
// })
axios.delete('',{
params:{
a:100,
b:100
}
}).then(response => {
console.log(response);
})
</script>