使用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
降级后原代码可直接正常运行。
验证步骤
- 重启Node.js服务
- 访问
/private接口,验证认证流程是否正常
内容的提问来源于stack exchange,提问作者Michael Behar
相关产品推荐
相关产品推荐

