axios请求失败 如何获取后端接口返回的状态码及错误信息

 这两天在写前端项目时候遇到个问题,后端异常做了统一处理,错误信息和提示都在返回的json中,在做校验或其他非正常情况下,返回错误的状态码,则axios直接报错,无法拿到后端返回的json。但是我需要向用户展示后端返回的json中的错误信息,用普通的catch方法只能获取到浏览器返回的400等错误提示,不能获取到后端返回的json,后经查阅得出下面方法:

axios.get('api/user/1')
  .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);
  });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值