11.请求超时与网络异常处理

本文介绍了如何在前端使用JavaScript的XMLHttpRequest对象来处理HTTP请求的超时问题,以及设置网络异常和请求超时的回调函数,以提升用户体验并确保正确响应网络状况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
          }
        }
      };
    });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值