2016-06-22 23 views
0

ユーザーの資格情報をチェックするミドルウェアを作成しようとしていますが、成功した場合はユーザー情報でJWTを作成します。私はクッキーを作成し、そのクッキー内にJWTを保存したいと思いますが、正しく動作させることができません。投稿時にログインメソッドを起動した後、「Can not POST/authenticate」というエラー404が表示されます。私は何が欠けていますか?NodeJS 404エラー

ルート:

app.post('/authenticate', function(req, res, next){ 
    middleware.login(req, res, next); 
}); 

ミドルウェア:あなたが実際に応答を送信しない、単に次のハンドラに実行を渡しているので、

exports.login = function(req, res, next){ 
    var username = req.body.username; 
    var password = req.body.password; 
    User.findByUsername(username,function(err, user){ 
     if(err){ 
      res.send({ success: false, message: 'Authentication failed.' }); 
     } 
     if (!user) { 
      res.send({ success: false, message: 'Authentication failed. User not found.' }); 
     } 
     if(user && !user.isuserenabled){ 
      res.send({ success: false, message: 'Authentication failed. User not found.' }); 
     } 
     if (!UserSchema.comparePassword(password,user.user_password)) { 
      res.send({ success: false, message: 'Authentication failed. User not found.' }); 
     } 
     res.cookie('yummyCookie', jwt.sign(
      //payload, secret, options, [callback] 
      { 
       id: user.user_id, 
       email: user.email, 
       name: user.firstname + " " + user.lastname, 
       role: user.role 
      }, 
      config.secret, // DO NOT KEEP YOUR SECRET IN THE CODE 
      {expiresIn: "1h"}, {secure: true, httpOnly: true})); 
     return next(); 
    }); 
}; 

答えて

0

あなたが404 not foundを受けている理由があります。実際に呼び出されるのはなので、別のミドルウェアが要求を処理することを期待しています。あなたのルートが実際に呼び出されるかなり基本的な例がありますが、実行はチェーンの責任において次のミドルウェアに渡されます。何もないので、あなたはエラーを受け取ります。

var express = require('express'); 
 

 
var app = express(); 
 

 
app.post('/test', (req, res, next) => { 
 
\t console.log('called'); 
 
\t next(); 
 
}); 
 

 
app.listen(5000);

これは、コンソールに「と呼ばれる」と書くが、それでもあなたは何ができるか404を返します。このようになります認証が成功した後、別のハンドラを追加します:

app.post('/authenticate', (req, res, next) => { 
 
    res.send('OK').end(); 
 
});

か、トンを組み込むことができますハットは、呼び出しの代わりにミドルウェア自身でログインします。next()

+0

最後に何かを送る必要がありますか(この場合は「OK」)、res.end()を呼び出すことができます。 ? –

+0

'res.end()'を呼び出すだけで、HTTPステータス200の空の本体が返されます –