本文介绍了在表达多个回调如何在app.get中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node的新手,所以如果我不明显,请原谅我.在node.js表达app.get函数的快速应用程序中,我们通常将route和view作为参数传递例如

I am newbie in node so please forgive me if i am not getting obvious.In node.js express application for app.get function we typically pass route and view as parameterse.g.

app.get('/users', user.list);

但是在 passport-google示例中,我发现它们是称为

but in passport-google example I found that they are calling it as

app.get('/users', ensureAuthenticated, user.list);

其中sureAuthenticated是一个函数

where ensureAuthenticated is a function

function ensureAuthenticated(req, res, next) {
    if (req.isAuthenticated()) { return next(); }
    res.redirect('/login')
}

简而言之,这意味着有多个在运行时被依次调用的回调.我尝试添加一些其他功能以使其看起来像

In short this means there are multiple callbacks which while running are called in series. i tried adding couple of more functions to make it look like

app.get('/users', ensureAuthenticated, dummy1, dummy2, user.list);

,我发现确保已连续调用Authenticated,dummy1,dummy2,user.list.

and i found ensureAuthenticated, dummy1, dummy2, user.list is getting called in series.

对于我的特定要求,我发现以上述形式顺序调用函数是一种非常优雅的解决方案,而不是使用异步序列.有人可以向我解释一下它是如何工作的,以及我一般如何实现类似的功能.

for my specific requirement i find calling functions sequentially in above form is quite elegant solution rather that using async series. can somebody explain me how it really works and how i can implement similar functionality in general.

推荐答案

在Express中,路径后的每个参数都按顺序调用.通常,这是一种实现中间件的方法(如您在提供的示例中所见).

In Express, each argument after the path is called in sequence. Usually, this is a way of implementing middleware (as you can see in the example you provided).

app.get('/users', middleware1, middleware2, middleware3, processRequest);

function middleware1(req, res, next){
    // perform middleware function e.g. check if user is authenticated

    next();  // move on to the next middleware

    // or

    next(err);  // trigger error handler, usually to serve error page e.g. 403, 501 etc
}

这篇关于在表达多个回调如何在app.get中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 22:29