当我尝试从授权标头中提取JWT令牌时,出现以下错误:
TypeError: JwtStrategy requires a function to retrieve jwt from requests (see
option jwtFromRequest)
at new JwtStrategy (C:\MEANauth app\node_modules\passport-jwt\lib\strategy.j
s:55:15)
at module.exports (C:\MEANauth app\config\passport.js:10:15)
at Object.<anonymous> (C:\MEANauth app\app.js:37:29)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
这是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.fromAuthHeaderWithScheme("jwt");
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts,function(jwt_payload,done){//here it points for error
User.getUserById(jwt_payload._id, function(err,user){
if(err){
return done(err, false);
}
if(user){
return done(null, user);
}
else{
return done(null, false);
}
});
}));
}
app.js:这是主文件
const passport =require("passport");
这是护照中间件
//passport middleware
app.use(passport.initialize());
app.use(passport.session());
//这是它指向错误的语句
require('./config/passport')(passport);
答案 0 :(得分:1)
只需在opts.JwtFromRequest
中将'J'更改为'j':
opts.jwtFromRequest =ExtractJwt.fromAuthHeaderWithScheme("jwt");