2017-05-24 8 views
0

ユーザーがログインしたいときにJWTトークンを作成するために、NodeJS用のJWT-Expressパッケージを使用しようとしました。残念ながら、パッケージでTypeErrorを受け取りました。私のコードに続いてjwt-expressパッケージを使用したTypeError

var express = require('express'); 
var app = express(); 

var jwt = require('jwt-express'); 
app.use(jwt.init('secret')); 

app.get('/login', function(req, res) { 
    var user = { 
     first: "Firstname", 
     last: "Lastname", 
     is_admin: true 
    }; 

    // we are using cookies so the JWT is 
    // automatically stored for us 
    var jwt = res.jwt({ 
     admin: user.is_admin, 
     name: user.first + ' ' + user.last 
    }); 

    // we now have access to the JWT Object 
    console.log(jwt); 

    // if we weren't using cookies, we could 
    // now send the token to the client 
    res.send(jwt.token); 
}); 

app.listen(8080); 

私は3行目でオブジェクトjwtjwt.init戻り未定義に等しくない何かへの呼び出しの両方のことを確認しました。

パッケージ内に何らかの形で間違いが付いているようです。 GET要求が処理される前でもシステムがクラッシュします。

エラーは次のとおりです。

TypeError: Cannot read property 'jwt-express' of undefined 
    at Object.<anonymous> (/Users/stuckenholz/auth/node_modules/jwt-express/jwt-express.js:218:36) 
    at Layer.handle [as handle_request] (/Users/stuckenholz/auth/node_modules/express/lib/router/layer.js:95:5) 
    at trim_prefix (/Users/stuckenholz/auth/node_modules/express/lib/router/index.js:317:13) 
    at /Users/stuckenholz/auth/node_modules/express/lib/router/index.js:284:7 
    at Function.process_params (/Users/stuckenholz/auth/node_modules/express/lib/router/index.js:335:12) 
    at next (/Users/stuckenholz/auth/node_modules/express/lib/router/index.js:275:10) 
    at expressInit (/Users/stuckenholz/auth/node_modules/express/lib/middleware/init.js:40:5) 
    at Layer.handle [as handle_request] (/Users/stuckenholz/auth/node_modules/express/lib/router/layer.js:95:5) 
    at trim_prefix (/Users/stuckenholz/auth/node_modules/express/lib/router/index.js:317:13) 
    at /Users/stuckenholz/auth/node_modules/express/lib/router/index.js:284:7 

任意のアイデア?

敬具...

答えて

0

req.cookiesは、ライン218で空であるように見えます:

token = req.cookies[this.options.cookie]; 

jwt-expressを初期化する前にクッキーを解析することを忘れないでください:

var express = require('express') 
var cookieParser = require('cookie-parser') 

var app = express() 
app.use(cookieParser()) 

https://github.com/expressjs/cookie-parser

+0

間違ったパッケージを確認したと思います。おそらくexpress-jwtを見てみると、既存のトークンのみをチェックすることができます。私はjwt-expressを使ってそれらを作成することもできました。 jwt-expressのドキュメントを[リンク](https://www.npmjs.com/package/jwt-express)で見ると、正しいコードを使用しました。 – LosWochos

+0

@LosWochosそうです、パッケージ名はちょっと混乱します。私は私の答えを変えました、それがあなたを助けることを願っています。 – Festo

+0

素晴らしい!私はクッキー部分を認識しませんでした。どうもありがとう。私は、トークンをクッキーに保存することを無効にすることができることも発見しました。 – LosWochos

関連する問題