前端判断网络状态并提示

在后台系统访问,有时候会遇到断网或者网络不好得时候,所以这里需求是在请求发送之前判断网络环境,如果断网给出提示,弱网超过一定时间提示请求超时

1、封装判断断网函数统一封装

这里使用得是window的一个属性navigator

复制代码
function checkConnectionStatus() {
  const networkType = window.navigator.onLine;
    if (!networkType) {
      // 网络速度慢,给出提示
      message({
        type: "error",
        message: "当前网络未连接,请检查网络!"
      });
      return false
    }
    return true
}
2、在请求封装的函数前先判断网络情况

如果断网直接提示,并不走请求逻辑

复制代码
/**
 * post方法,对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, params, isLoading = true) {
  // 在发送请求之前判断网络状态
  const flag = checkConnectionStatus()
  if(!flag) return
  if (isLoading == true) {
    var loadingInstance = Loading.service({
      lock: true,
      text: "加载中...",
      background: "rgba(255, 255, 255, 0.3)"
    });
  }
  return new Promise((resolve, reject) => {
    Axios.post(url, QS.stringify(params))
      .then(res => {
        if (loadingInstance) {
          setTimeout(() => {
            loadingInstance.close();
          }, 0);
        }
        resolve(res.data);
      })
      .catch(err => {
        if (loadingInstance) {
          setTimeout(() => {
            loadingInstance.close();
          }, 0);
        }        
        reject(err.data);
      });
  });
}
3、弱网情况下提示请求超时

这里需要在响应拦截器中做判断

3.1、设定超时时间
复制代码
// 设置请求超时
Axios.defaults.timeout = 20000;
3.2、拦截器判断
复制代码
Axios.interceptors.response.use(
···
// 服务器状态码不是成功的情况
  error => {
    if (error.message.includes("timeout")) {
      message({
        type: "error",
        message: "网络连接超时,请检查网络"
      });
      return Promise.reject(error.response);
    } else if (error.response.status) {
        // 其他错误,直接抛出错误提示
        default:
          break;
      }
      return Promise.reject(error.response);
    }
  }
)

这样子就可以啦,是不是很容易!!!

相关推荐
牛奶4 分钟前
Vue 基础理论 & API 使用
前端·vue.js·面试
牛奶10 分钟前
Vue 底层原理 & 新特性
前端·vue.js·面试
anOnion28 分钟前
构建无障碍组件之Radio group pattern
前端·html·交互设计
pe7er31 分钟前
状态提升:前端开发中的状态管理的设计思想
前端·vue.js·react.js
SoaringHeart1 小时前
Flutter调试组件:打印任意组件尺寸位置信息 NRenderBox
前端·flutter
晚风予星2 小时前
Ant Design Token Lens 迎来了全面升级!支持在 .tsx 或 .ts 文件中直接使用 Design Token
前端·react.js·visual studio code
sunny_2 小时前
⚡️ vite-plugin-oxc:从 Babel 到 Oxc,我为 Vite 写了一个高性能编译插件
前端·webpack·架构
GIS之路2 小时前
ArcPy 开发环境搭建
前端
林小帅4 小时前
【笔记】OpenClaw 架构浅析
前端·agent
林小帅4 小时前
【笔记】OpenClaw 生态系统的多语言实现对比分析
前端·agent