Ajax学习日志(六)—— ajax错误处理

一、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学习日志(七)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值