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

Node.js中Passport-JWT验证受保护路由报错求助

解决Passport-JWT配置中的两个常见错误

嘿,我看你在给Node.js项目配置Passport-JWT保护路由的时候遇到了两个棘手的问题,咱们一步步来搞定它们:

第一个错误:TypeError: require(...) is not a function

这个错误出现在server.js执行require('./config/passport')(passport)的时候,原因很简单——你在passport配置文件里的导出语句写错了!

你写的是module.export,但正确的Node.js模块导出语法是module.exports(多了一个s)。这个拼写错误直接导致你的配置函数没有被正确导出,所以server.js里尝试把require的结果当作函数调用时,就会抛出“不是函数”的错误。

第二个错误:Unknown authentication strategy "jwt"

这个错误其实是第一个问题的连锁反应:因为你的passport配置函数根本没被正确执行,所以passport.use(new jwtStrategy(...))这行代码压根没跑起来,自然就没有注册名为jwt的认证策略。当路由里调用passport.authenticate('jwt')时,Passport找不到对应的策略,就会抛出这个错误。


修正后的完整代码

1. 修正passport配置文件(./config/passport.js)

const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const mongoose = require('mongoose');
const User = mongoose.model('users');
const keys = require('../config/keys');

const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = keys.secretOrKey;

// 修正导出语法,同时补充完整认证逻辑的done调用
module.exports = (passport) => {
  passport.use(
    new JwtStrategy(opts, (jwt_payload, done) => {
      console.log(jwt_payload);
      // 根据JWT payload里的用户ID查询数据库
      User.findById(jwt_payload.id)
        .then(user => {
          if (user) {
            // 找到用户,将用户信息传递给后续中间件
            return done(null, user);
          }
          // 未找到用户,返回false表示认证失败
          return done(null, false);
        })
        .catch(err => console.error(err));
    })
  );
};

2. 确保server.js里的Passport初始化顺序正确

const express = require('express');
const passport = require('passport');
const app = express();

// 初始化Passport
app.use(passport.initialize());
// 加载Passport配置
require('./config/passport')(passport);

// ... 其他路由和中间件配置

3. 受保护路由的小优化(可选)

注意你的路由注释里的@access应该是Private(因为是受保护路由),同时可以返回认证后的用户信息:

// @route GET /users/current
// @desc Return the current user (owner of the JWT token)
// @access Private
router.get('/current', passport.authenticate('jwt', { session: false }), (req, res) => {
  // 认证成功后,Passport会将用户信息挂载到req.user上
  res.json({ 
    msg: "Success",
    user: {
      id: req.user.id,
      name: req.user.name,
      email: req.user.email
    }
  });
});

完成这些修正后,重启你的服务器,再用Postman携带有效Bearer Token访问/users/current路由,应该就能正常返回成功响应了。

内容的提问来源于stack exchange,提问作者J.G.Sable

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:06:27