axios在catch中获取响应状态码

本文详细介绍了如何处理axios请求中遇到的各种错误,包括服务器响应错误、请求未收到响应以及设置请求时触发的错误,并提供了具体的代码示例。

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

以下 是 对 axios 请求 错误的处理 ( 困扰我好长时间 的 问题 终于 解决了!)

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

下图控制台 打印出的 结果 : 

Axios是一个流行的基于Promise的HTTP客户端,用于浏览器和Node.js。二次封装Axios是为了提供更简洁、易用的API,并通常会包含错误处理和状态码管理。当处理不同状态码时,常见的做法是在axios请求拦截器(interceptors)中进行: 1. **设置全局响应拦截器**: ```javascript import axios from 'axios'; import { MessageBox } from 'element-ui'; axios.interceptors.response.use( (response) => { // 对成功的状态码(如200)进行处理 if (response.status >= 200 && response.status < 300) { return response.data; } // 如果状态码在自定义范围内,也可以直接返回数据 // 如:处理401未授权等特定状态码 if (response.status === 401) { handleUnauthorized(response); } // 其他状态码可以按需处理 return response; }, (error) => { // 对非成功的状态码(如500,404等)进行处理 if (error.response) { switch (error.response.status) { case 404: handleNotFound(error); break; default: handleServerError(error); } } else { // 非网络错误,如网络中断等情况 handleNetworkError(error); } return Promise.reject(error); }); ``` 这里`handleUnauthorized`, `handleNotFound`, 和 `handleServerError` 是自定义函数,负责根据不同的状态码显示相应的提示信息,或者执行其他业务逻辑。 2. **针对特定操作的拦截器**: 如果某个功能需要特殊处理某些状态码,可以在那个函数内部添加额外的检查: ```javascript function fetchData() { axios.get('api/data') .then((response) => { // 特定操作对成功或特定状态码的处理 if (response.status === 200 || response.status === 201) { handleSuccessfulFetch(response); } else { throw new Error(`Unexpected status code: ${response.status}`); } }) .catch((error) => { // 错误处理 }); } function handleSuccessfulFetch(response) { // 处理获取到的数据 } ```
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Gleason.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值