Passport auth卡在控制器中?

时间:2017-11-03 17:50:30

标签: javascript node.js typescript passport.js

我尝试将路由转发给控制器,但对Passport.js来说似乎不适合我

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

现在,唯一不起作用的路线是具有Passport的路线。

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
}

我正在使用TypeScript

1 个答案:

答案 0 :(得分:2)

Passport是异步的。它通常用作传递回调的中间件。例如,文档有这个例子:

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

这里要记住的是passport.authenticate返回一个接受(req, res, next)的函数。然后它会对该数据执行操作,并在完成后调用next。在您的代码中,您正在调用authenticate(返回一个函数),然后对它执行任何操作。我有一些建议。

首先是通过简化事物来降低噪音。根据框架,您通常可以传递一堆函数来处理路由。在这种情况下,您只需要一个。

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个参数传递给控制器​​。这不是必需的。在大多数情况下,它们是相同的。