1.请求超时
请求时间过长的时候需要进行处理
为了呈现请求超时的效果,我们在路由规则里设置 3s 以后服务器才返回结果
app.get("/delay", (request, response) => {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "*");
setTimeout(() => {
response.send("HELLO IE");
}, 3000);
});
设置请求超时就取消请求,在发送 Ajax 请求的步骤里设置,通过 xhr 对象的 timeout 属性
xhr.timeout = 2000;
还可以设置请求超时的回调,通过 xhr 对象的 ontimeout 属性设置
xhr.ontimeout = function() {
alert('请求超时...已取消请求')
};
整理如下
const result = document.querySelector("#result");
result.addEventListener("mouseover", () => {
const xhr = new XMLHttpRequest();
// 设置等待时间
xhr.timeout = 2000;
// 设置超时以后的回调函数
xhr.ontimeout = function () {
alert("请求超时...已取消请求");
};
xhr.open("GET", "http://127.0.0.1:8000/delay");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
result.innerHTML = xhr.response;
}
}
};
});
2.网络异常
为了实现网络异常效果,通过后台控制器去设置
可以通过 xhr 对象的 onerror 属性去设置网络异常的回调函数
xhr.onerror = function () {
alert("你的网络有些异常");
};
整理如下
const result = document.querySelector("#result");
result.addEventListener("mouseover", () => {
const xhr = new XMLHttpRequest();
// 设置请求等待时间
xhr.timeout = 2000;
// 设置请求超时后的回调
xhr.ontimeout = function () {
alert("请求超时...已取消请求");
};
// 设置网络异常的回调
xhr.onerror = function () {
alert("你的网络有些异常");
};
xhr.open("GET", "http://127.0.0.1:8000/delay");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
result.innerHTML = xhr.response;
}
}
};
});