You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS中调用其他接口执行成功却进入catch代码块问题排查

问题解析:明明接口执行成功,为何axios调用却进入catch?

先还原你的代码场景:
你有两个核心接口,/api/v1/update负责数据更新并返回成功响应:

exports.update = (req, res) => {
  Data.update({salary: 1})
    .then(data => {
      console.log("All good")
      return res.status(200).send({message: "OK"})
    })
    .catch(error => {
      console.log("Oh Crap!")
      return res.status(400).send(error)
    })
}

/api/v1/process接口通过axios调用上述update接口:

exports.process = (req, res) => {
  axios.get('http://localhost:8008/api/v1/update')
    .then(data => {
      console.log("You got it")
      return res.status(200).send(data)
    })
    .catch(error => {
      console.log("Not working!")
      return res.status(400).send(error)
    })
}

控制台输出显示All good(说明update接口确实执行成功),但紧接着Not working!,说明process接口意外进入了catch块。

问题根源

你自己已经定位到了关键:直接返回axios的完整响应对象会触发Converting circular structure to JSON错误。

这是因为axios返回的data参数并不是update接口返回的纯响应体,而是一个包含整个请求上下文的对象——里面嵌套了request实例、response实例等存在循环引用的属性(比如response对象里的request又指向了当前response)。当你用res.send(data)时,Express会尝试把这个对象序列化为JSON,遇到循环引用就会抛出错误,进而触发catch块。

解决方法

只需要提取axios响应中真正来自update接口的返回数据即可,也就是response.data(第一个response是axios的响应容器,第二个data是update接口实际返回的内容):

exports.process = (req, res) => {
  axios.get('http://localhost:8008/api/v1/update')
    .then(response => {
      console.log("You got it")
      // 仅返回接口的响应体内容
      return res.status(200).send(response.data)
    })
    .catch(error => {
      console.log("Not working!")
      return res.status(400).send(error)
    })
}

这样就避开了序列化循环引用对象的问题,process接口就能正常进入then块返回结果了。

内容的提问来源于stack exchange,提问作者Mr.P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 23:12:49