Axios中请求成功了,却仍然被catch捕获

在vue中做一个请求用户收藏的功能,请求成功发出且服务器也响应了状态码,但axios的返回仍然被catch捕获了,不能通过then得到返回数据。

通过查看Axios的官方文档的错误处理一节,

catch到的不一定是请求失败了,可以通过更多的输出查看错误信息。

编写一个获取用户收藏信息的函数:

function userFavorite (username,subject_type,type,limit,offset) {
  return axios.get('/v0/users/' + username+'/collections' , {
    username, //必需
    subject_type,
    type,
    limit,
    offset,
  })
}

在其他组件中引入该函数,然后调用,在catch中插入更多的log语句,反应报错

//获取用户收藏
userFavorite(username,2,3,30,0).then( res => {
      console.log(res.data[1].name_cn)
      for  (let item=0; item < Math.min(8, res.data.length); item++){
        userProfile.addFavorList(res.data[i].name_cn)
      }
    })
    .catch(function (error) {
    if (error.response) {
      // 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // 请求已经成功发起,但没有收到响应
      console.log(error.request);
    } else {
      // 发送请求时出了点问题
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

这样可以查看具体的报错,由此得到我的错误是接口函数调用时res.data[i].name_cn取不到该值(undefined),详细查看浏览器的网络响应,把循环和调用中的都改为:res.data.data[item].subject.name_cn就成功了。

后端接口来源于Bangumi API

文章来源于我的个人博客:Axios中请求成功了,却仍然被catch捕获

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值