JSON Web Tokens实现项目报错:expressjwt is not a function
问题:expressjwt is not a function 错误
报错信息
TypeError: expressjwt is not a function at jwt (D:\jwt-implementation\routes\config\jwt.js:8:12) at Object.<anonymous> (D:\jwt-implementation\app.js:26:9) at Module._compile (node:internal/modules/cjs/loader:1105:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Module.require (node:internal/modules/cjs/loader:1005:19) at require (node:internal/modules/cjs/helpers:102:18) at Object.<anonymous> (D:\jwt-implementation\bin\www:7:11) at Module._compile (node:internal/modules/cjs/loader:1105:14) [nodemon] app crashed - waiting for file changes before starting...
原代码实现
const expressjwt = require("express-jwt") const config = require('../../nodemon.json') function jwt() { const { secret } = config return expressjwt({ secret, algorithm: ["RS256", "HS256"] }).unless({ path: [ //public routes that don't require authentication "users/authenticate" ] }) } module.exports = jwt;
解决方法
这个错误是因为express-jwt v8及以上版本的导出方式发生了变化,不再直接导出默认函数。需要修改导入语句,解构出expressjwt函数:
修改后的代码:
const { expressjwt } = require("express-jwt") // 改为解构导入 const config = require('../../nodemon.json') function jwt() { const { secret } = config return expressjwt({ secret, algorithms: ["RS256", "HS256"] }).unless({ // 参数名改为algorithms(复数) path: [ // 无需鉴权的公开路由 "/users/authenticate" // 建议添加开头斜杠,避免路径匹配问题 ] }) } module.exports = jwt;
另外注意两个细节:
- 配置JWT算法的参数名是
algorithms(复数形式),不是原代码中的algorithm,这是常见错误点 - 路由路径建议加上开头的
/,确保路径匹配准确
内容的提问来源于stack exchange,提问作者Chelsea jain
相关产品推荐
相关产品推荐

