NodeJS TypeError('JwtStrategy需要一个秘密或密钥');

我已经尝试了我replace的JwtStrategy实现

  1. User.findOne({id:jwt_payload.id})

  2. User.getUserById(jwt_payload._doc._id,(err,user)

这是在user.js文件里面我runnning index.js时得到的错误是: –

H:\rprfinal\node_modules\passport-jwt\lib\strategy.js:29 throw new TypeError('JwtStrategy requires a secret or key'); ^ TypeError: JwtStrategy requires a secret or key at new JwtStrategy (H:\rprfinal\node_modules\passport-jwt\lib\strategy.js:29:15) at module.exports (H:\rprfinal\config\passport.js:10:18) at Object.<anonymous> (H:\rprfinal\index.js:42:29) at Module._compile (module.js:569:30) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Function.Module.runMain (module.js:605:10) at startup (bootstrap_node.js:158:16) at bootstrap_node.js:575:3 [nodemon] app crashed - waiting for file changes before starting... 

user.js文件中: –

 module.exports.getUserById = function(id, callback){ User.findById(id, callback); } 

index.js文件: –

  //Body parser Middleware app.use(bodyParser.json()); //Passport Middleware app.use(passport.initialize()); app.use(passport.session()); require('./config/passport')(passport); app.use('/users',users); 

passport.js文件: –

 const JwtStrategy = require('passport-jwt').Strategy; const ExtractJwt = require('passport-jwt').ExtractJwt; const User = require('../models/user'); const config = require('../config/database'); module.exports = function(passport){ let opts = {}; opts.jwtFromRequest = ExtractJwt.fromAuthHeader(); opts.secretOrKey = config.secret; passport.use(new JwtStrategy(opts, (jwt_payload, done) => { User.getUserById(jwt_payload._doc._id, (err, user) => { if(err){ return done(err, false); } if(user){ return done(null, user); } else{ return done(null, false); } }); })); } 

users.js包含Register和Authenticate

  // Authenticate router.post('/authenticate',(req, res, next) => { const username = req.body.username; const password =req.body.password; User.getUserBYUsername(username, (err, user) => { if(err) throw err; if(!user){ return res.json({success: false,msg: 'User not found'}); } User.comparePassword(password,user.password, (err, isMatch) => { if(err) throw err; if(isMatch){ const token = jwt.sign(user, config.secret, { expiresIn: 604800 // 1 Week }); res.json({ success: true, token: 'JWT '+token, user: { id: user._id, name:user.name, username: user.username, email: user.email } }); } else { return res.json({success: false, msg: 'Wrong password'}); } }); }); });