一、ajax错误处理
1.1)需了解的知识
res.status(code)
Sets the HTTP status for the response
// 403错误: 一种在网站访问过程中,常见的错误提示,表示资源不可用。服务器理解客户的请求,但拒绝处理它,通常由于服务器上文件或目录的权限设置导致的WEB访问错误。
// res.end(): Ends the response process
res.status(403).end()
// 400错误:
// 1)bad request: 表示"错误的请求"
// 2)invalid hostname: 表示"不存在的域名"
// 400报错原因:
// 1)前端提交数据的字段名称或者是字段类型和后台的实体类不一致,导致无法封装;
// 2)前端提交的到后台的数据应该是 json 字符串类型,而前端没有将对象转化为字符串类型;
// 400报错解决方法:
// 1)对照字段名称,类型保证一致性
// 2)使用 stringify 将前端传递的对象转化为字符串: data: JSON.stringify(param);
// res.send(): Sends the HTTP response.
res.status(400).send('Bad Request')
// res.sendFile(): Transfers the file at the given path(在给定的路径上传输文件)
res.status(404).sendFile('/absolute/path/to/404.png')
1.2)在app.js创建新路由
app.get('/error', (req, res)=>{
res.status(400).send("not ok!");
})
1.3) 在public文件夹新建一个html文件
<button id="btn">发送Ajax请求</button>
<script>
// 绑定按钮
let btn = document.getElementById("btn");
// 创建按钮点击事件
btn.onclick = function () {
// 创建ajax对象
let xhr = new XMLHttpRequest();
// 确定请求方式以及请求路径
xhr.open('get', 'http://localhost:8822/error');
// 发送请求
xhr.send();
// 获取服务器端响应到客户端的数据
xhr.onload = function () {
console.log(xhr.responseText);
// xhr.status: 获取Http状态码
// Http状态码: 表示请求的处理结果,是服务器返回的
// Ajax状态码: 表示Ajax请求的过程状态,是Ajax对象返回的
console.log(xhr.status)
if(xhr.status === 400){
alert("出错!");
}
}
// 当网络中断时,会触发onerror事件
xhr.onerror = function () {
alert('网络中断,无法发送Ajax请求');
}
}
</script>
1.4) 在浏览器运行
当涉及断网时,将触发onerror事件 ——此处用“离线”来模拟断网的情况
1.5) ajax错误处理
———————————————————————————————————————
上一篇:
Ajax学习日志(五)
下一篇:
Ajax学习日志(七)