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

为何Express接口中.then已成功返回响应,catch语句仍被触发?

问题分析与解决

嗨,这个问题的核心是你在catch里的写法出错啦!

你现在写的.catch( console.log("error") ),其实是直接执行了console.log("error"),然后把它的返回值(也就是undefined)传给了catch方法。而catch方法需要接收一个函数作为参数——只有当Promise被rejected(也就是请求出错)的时候,这个函数才会被调用。

但你当前的写法会导致:不管axios请求成功还是失败,代码执行到这一行时,都会先运行console.log("error"),所以哪怕then里已经成功返回响应了,这个错误日志还是会打印出来。

修正方案

方案1:把catch的参数改成函数

把console.log("error")包装成一个箭头函数,这样只有当请求真的出错时,才会执行这个日志:

const express = require("express");
const router = express.Router();
const { API_KEY, API_URL } = process.env
const axios = require("axios")
router.get("/", async (req, res) => {
  console.log(API_URL + API_KEY)
  await axios.get(API_URL + API_KEY + "&count=9")
  .then((response) => {
    res.send(response.data)
  })
  .catch(err => { // 这里改成函数形式
    console.log("error", err) // 建议同时打印错误对象,方便排查问题
  })
})
module.exports = router

方案2:用async/await搭配try/catch(更推荐)

既然你已经用了async函数,其实完全可以抛弃.then/.catch的回调写法,改用更直观的try/catch,这样代码逻辑更清晰,也不容易出错:

const express = require("express");
const router = express.Router();
const { API_KEY, API_URL } = process.env
const axios = require("axios")
router.get("/", async (req, res) => {
  try {
    console.log(API_URL + API_KEY)
    const response = await axios.get(API_URL + API_KEY + "&count=9")
    res.send(response.data)
  } catch (err) {
    console.log("error", err)
    // 这里还可以给用户返回错误响应,比如res.status(500).send("请求出错")
  }
})
module.exports = router

额外提示

你同时混用了await和.then/.catch,其实这两种写法选一种就够了。await本身就是用来等待Promise完成的,搭配try/catch处理错误,代码的可读性会比回调嵌套高很多哦~

内容的提问来源于stack exchange,提问作者codingrook

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 14:17:44