<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>XHR</title>
</head>
<body>
<div>
<button onclick="testGet()">GET请求</button>
<button onclick="testPost()">POST请求</button>
<button onclick="testPut()">PUT请求</button>
<button onclick="testDelete()">DELETE请求</button>
</div> <script>
function testGet() {
axios({
url: "http://localhost:3000/posts",
params: {
id: 1
}
}).then(
response => {
console.log(response);
},
error => {
console.log(error.message);
}
);
} function testPost() {
axios({
url: "http://localhost:3000/posts",
method: "POST",
data: {
title: "--POST添加上去的",
author: "--POST添加---",
id: 4
}
}).then(
response => {
console.log(response);
},
error => {
console.log(error.message);
}
);
} // axios 简单封装
function axios({ url, method = "GET", params = {}, data = {} }) {
// 返回一个promise对象
return new Promise((resolve, reject) => { // 处理metho(转大写)
method = method.toUpperCase()
// 处理query参数(拼接到url上) id=1&aaa=ccc
/*{
id: 1,
aaa: ccc
}*/
let queryString = "";
Object.keys(params).forEach(key => {
queryString += `${key}=${params[key]}&`;
});
// 判断queryString有没有值
if (queryString) {
// 去除最后的&
queryString = queryString.substring(0, queryString.length - 1);
// 接到url上
url += "?" + queryString;
}
console.log(queryString);
// 1.执行异步ajax请求
// 创建xhr对象
const request = new XMLHttpRequest(); // 打开链接(初始化请求,没有请求)
request.open(method, url, true);
// 发送请求
if (method === "GET") {
request.send();
} else if (method === "POST") {
request.setRequestHeader(
"Content-Type",
"application/json;charset=utf-8"
); // 告诉服务器请求体的格式是JSON格式
request.send(JSON.stringify(data)); // 发送JSON格式的请求体参数
} //绑定状态改变的监听
request.onreadystatechange = function() {
// 如果请求没有完成,直接结束
if (request.readyState !== 4) {
return;
}
// 如果响应状态码在[200,300)之间表示请求成功,否则失败
const { status, statusText } = request;
if (status >= 200 && status < 300) {
// 准备结果数据对象response
const response = {
data: JSON.parse(request.response),
status,
statusText
};
// 2.1如果请求成功了,调用resolve()
resolve(response);
} else {
// 2.2如果请求失败,调用reject()
reject(new Error("request error status is " + status));
}
};
});
}
</script>
</body>
</html>