2016-04-10 8 views
15

https://devdactic.com/restful-api-user-authentication-1/からチュートリアルを習得しました。しかし、私はこの部分。ここNodeJS jwtStrategyには、リクエストからエラーを取得する関数が必要です。

passport.use(new JwtStrategy(opts, function(jwt_payload, done) 

にエラーが発生しましたが、私は

/home/chibi/Documents/connect/project/node_modules/passport-jwt/lib/strategy.js:39 
throw new TypeError('JwtStrategy requires a function to retrieve jwt f 
     ^
TypeError: JwtStrategy requires a function to retrieve jwt from requests (see option jwtFromRequest) 
at new JwtStrategy (/home/chibi/Documents/connect/project/node_modules/passport-jwt/lib/strategy.js:39:15) 
at module.exports (/home/chibi/Documents/connect/project/config/passport.js:10:16) 
at Object.<anonymous> (/home/chibi/Documents/connect/project/server.js:30:29) 
at Module._compile (module.js:456:26) 
at Object.Module._extensions..js (module.js:474:10) 
at Module.load (module.js:356:32) 
at Function.Module._load (module.js:312:12) 
at Function.Module.runMain (module.js:497:10) 
at startup (node.js:119:16) 
at node.js:902:3 

ソリューションとは何である「server.js」ノードを実行するとエラーになりますか?

+0

おかげでまた、このチュートリアルをやってこのエラーが発生しました – HappyCoder888

答えて

38

私はあなたが 'passport-jwt' 2.0.0を使用していると思うので、チュートリアルで使用されているv1.x.xからいくつかの変更が加えられました。 optsでは、別のオプションjwtFromRequestを渡して、jwtペイロードを探す場所を指定する必要があります。

official documentationから
var JwtStrategy = require('passport-jwt').Strategy, 
    ExtractJwt = require('passport-jwt').ExtractJwt; 
var opts = {}; 
opts.jwtFromRequest = ExtractJwt.fromAuthHeader(); 
opts.secretOrKey = config.secret; 
passport.use(new JwtStrategy(opts, function(jwt_payload, done) { 
    User.findOne({id: jwt_payload.id}, function(err, user) { 
     if (err) { 
      return done(err, false); 
     } 
     if (user) { 
      done(null, user); 
     } else { 
      done(null, false); 
      // or you could create a new account 
     } 
    }); 
})); 
+11

'' 'ExtractJwt.fromAuthHeaderに直面している人は関数' 'のエラーではないので、passport-jwt 2.0から3.0への急な変更があります! ** fromAuthHeaderAsBearerToken **のような他の抽出プログラムを使うべきです。 https://www.npmjs.com/package/passport-jwt#included-extractorsで抽出者のリストを確認してください。 –

14

、あなたが使用する必要がありますJWTを使用して3.xへ2.xからの移行:代わりに古いの

ExtractJwt.fromAuthHeaderWithScheme('jwt') 

:この投稿

ExtractJwt.fromAuthHeader() 
+0

以前は検証済みのソリューションを使用していましたが、新しいプロジェクトを開始したときに、私が3.xを使用していたことに気づきませんでした。 –

関連する問題