2017-11-03 6 views
0

私はコントローラに私のルートを転送しようとしたが、それはPassport.jsPassport認証がコントローラにスタックされていますか?

router.get('/login', (req, res, next) => UserController.getLogin(req, res, next)); 
router.post('/login', (req, res, next) => UserController.postLogin(req, res, next)); 

と私のために動作するようには思えない、動作しないルートだけが特別パスポートを持つものです。

static getLogin(req: Request, res: Response, next: NextFunction) { 
... 
} 
static postLogin(req: Request, res: Response, next: NextFunction) { 

     passport.authenticate('local', { 
      successRedirect: '/success', 
      failureRedirect: '/failed' 
     }); 
     // res.send('hello from POST'); would work 
} 

私は

答えて

1

パスポートが非同期である活字体を使用しています。これはコールバックを渡されるミドルウェアとしてよく使われます。例えば、ドキュメントは、この例があります:

app.post('/login', passport.authenticate('local', { successRedirect: '/', 
               failureRedirect: '/login' })); 

ここで覚えておくべき事はpassport.authenticate(req, res, next)を受け入れる関数を返すということです。その後、そのデータに作用し、完了したらnextを呼び出します。あなたのコードでは、authenticate(関数を返す)を呼び出していて、何もしません。私はいくつかの提案があります。

最初は物事を単純化することでノイズを減らすことです。フレームワークによっては、通常、ルートを処理するための関数のスタックを渡すことができます。この場合、必要なのは1つだけです。

router.post('/login', passport.authenticate('local', { 
    successRedirect: '/success', 
    failureRedirect: '/failed' 
})) 

auth以上のことをしたい場合は、より多くの機能を渡すことができます。

router.post('/login', 
    passport.authenticate('local', { 
     successRedirect: '/success', 
     failureRedirect: '/failed' 
    }), 
    UserController.doThing // accepts (req, res, next) 
) 

私は、同じ3つのパラメータをコントローラに渡すための無名関数を作成していないことに気づくでしょう。それは必要はありません。ほとんどの目的のために同じです。

+0

私は[link] https://github.com/Microsoft/TypeScript-Node-Starter/blob/master/src/controllers/user.ts [/ link]をちょっと試してみましたが、コントローラのapp .post( "/ login"、userController.postLogin); 'このように、構造がより整理されるようになります。それは正しいアプローチではありませんか? – Dawid

+1

そのパターンに従うことができます。もしそうなら、あなたは 'authenticate'の最終実行を追加し、' req、res、next'を渡したいでしょう。 '... failureRedirect: '/ failed'})'(req、res、next) ' – ktilcu

+0

ありがとう! 私は実際に関数を自己呼び出しするのを忘れました 'passport.authenticate( 'local'、{...})(req、res、next);'うまく動作します – Dawid

関連する問題