网络畅通,服务器端能接收到请求,服务器端返回的结果不是预期结果。 可以判断服务器端返回的状态码,分别进行处理。xhr.status获取http状态码网络畅通, 服务器端没有接收到请求,返回404状态码。 检查请求地址是否错误。网络畅通, 服务器端能接收到请求,服务器端返回500状态码。 找后端程序员网络中断,请求无法发送到服务器端。 会触发xhr对象下面的onerror事件,在onerror事件处理函数中对错误进行处理。
app.get('/error',(req,res)=>{
res.status(400).send('hello');
})
var btn = document.querySelector("#btn");
btn.onclick = function(){
var xhr = new XMLHttpRequest;
xhr.open('get','http://localhost/error');
xhr.send();
xhr.onload = function(){
console.log(xhr.responseText)
console.log(xhr.status);
if(xhr.status === 400){
alert('请求出错');
}
}
xhr.onerror = function(){
alert('网络中断')
}
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-54711.html