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

使用express-jwt的Node.js后端API出现TypeError: cb is not a function错误求助

解决Express+JWT对接Auth0时的TypeError: cb is not a function错误

错误信息

TypeError: cb is not a function
at secretProvider

问题代码

const express = require('express')
const bodyParser = require('body-parser')
const { expressjwt: jwt } = require("express-jwt");
const jwksRsa = require('jwks-rsa');
const envVariables = require('./env-variables.json');
const db = require('./queries')
const port = 3000
const app = express()
app.use(bodyParser.json())
app.use(
  bodyParser.urlencoded({
    extended: true,
  })
)

app.use(jwt({
  // Dynamically provide a signing key based on the kid in the header and the singing keys provided by the JWKS endpoint.
  secret: jwksRsa.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: `https://${envVariables.auth0Domain}/.well-known/jwks.json`,
  }),

  // Validate the audience and the issuer.
  audience: envVariables.apiIdentifier,
  issuer: `https://${envVariables.auth0Domain}/`,
  algorithms: ['RS256']
}));
app.get('/private', (req, res) => res.send('Only authenticated users can read this message.'));
app.get('/users', db.getUsers)
app.get('/users/:id', db.getUserById)
app.post('/users', db.createUser)
app.put('/users/:id', db.updateUser)
app.delete('/users/:id', db.deleteUser)

app.listen(port, () => {
  console.log(`App running on port ${port}.`)
})

问题原因

该错误源于express-jwt v7+版本与旧版jwks-rsa的接口不兼容:express-jwt v7之后改用Promise风格的密钥提供者,而旧版jwks-rsa的expressJwtSecret方法仍采用回调式设计,两者调用逻辑不匹配触发报错。

解决方法

方法1:升级jwks-rsa到兼容版本

执行命令更新依赖:

npm install jwks-rsa@latest

确保jwks-rsa版本≥2.0.0,该版本已适配express-jwt v7的Promise接口,无需修改现有代码。

方法2:降级express-jwt到v6版本

若不想升级jwks-rsa,可将express-jwt降级到仍支持回调式密钥提供者的v6版本:

npm install express-jwt@6.1.0

降级后原代码可直接正常运行。

验证步骤

  1. 重启Node.js服务
  2. 访问/private接口,验证认证流程是否正常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 23:15:55