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

Node.js带回调函数调用遇阻:回调未返回问题排查求助

问题分析与解决方案

嘿,我一眼就瞅出问题所在了!你的回调函数永远不执行,核心原因出在checkTokenAlive这个函数里——它只在token过期或者token还未生效这两种错误场景下调用了回调cb,但如果token是完全有效的,函数就直接走完了,根本没触发回调!

具体问题点

看你的checkTokenAlive代码:

checkTokenAlive = (decoded, cb) => {
  const now = Date.now().valueOf() / 1000
  if (typeof decoded.exp !== 'undefined' && decoded.exp < now) {
    cb(`token expired: ${JSON.stringify(decoded)}`)
  }
  if (typeof decoded.nbf !== 'undefined' && decoded.nbf > now) {
    cb(`token not yet valid: ${JSON.stringify(decoded)}`)
  }
}

当token的exp大于当前时间,且nbf小于当前时间(也就是token完全有效)时,两个if条件都不满足,函数就没有任何代码去调用cb,导致你的回调永远处于等待状态,自然console.log('I am here')永远不会打印。

另外还有个潜在问题:你直接把token字符串传给了checkTokenAlive,但函数里直接访问decoded.exp和decoded.nbf——如果没先把token解析成包含这些字段的对象,那这两个属性根本不存在,同样会导致回调不执行。

修复方案

1. 给checkTokenAlive添加有效token的回调调用

在函数末尾加上cb(null),表示token有效,没有错误:

checkTokenAlive = (decoded, cb) => {
  const now = Date.now().valueOf() / 1000
  // 用return避免多次调用cb
  if (typeof decoded.exp !== 'undefined' && decoded.exp < now) {
    return cb(`token expired: ${JSON.stringify(decoded)}`)
  }
  if (typeof decoded.nbf !== 'undefined' && decoded.nbf > now) {
    return cb(`token not yet valid: ${JSON.stringify(decoded)}`)
  }
  // 关键:token有效时必须调用回调
  cb(null)
}

2. 确保token被正确解析

你需要先把token字符串解析成包含exp和nbf的对象,推荐使用jsonwebtoken库的decode或verify方法(verify还能验证签名,更安全):

const jwt = require('jsonwebtoken') // 先执行 npm install jsonwebtoken 安装

checkTokenAuthenticated = (req, res, next) => {
  let token = req.body.token;
  if (!token) {
    return res.status(400).end('No token provided')
  }
  let decoded;
  try {
    // 用decode只解析内容,不验证签名;如果需要验证签名用jwt.verify(token, 你的密钥)
    decoded = jwt.decode(token);
  } catch (err) {
    return res.status(400).end('Invalid token format')
  }
  checkTokenAlive(decoded, function (err) {
    console.log('I am here'); // 现在应该会执行了
    if (err) {
      console.log(err)
      return res.status(400).end(err)
    }
    return next()
  });
}

这样修改后,不管token是有效还是无效,回调都会被触发,你的路由验证逻辑就能正常运行啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 18:52:40