如前所述,可以提供多个回调函数,并像中间件一样处理请求。它们可以采用函数、函数数组或两者组合的形式,如以下示例所示。
例如:
app.get('/example/b', function (req, res, next) {
console.log('the response will be sent by the next function ...')
next()
}, function (req, res) {
res.send('Hello from B!')
})
这样做的目的是什么?我们不能简单地使用:
app.get('/example/b', function (req, res) {
console.log('the response will be sent by the next function ...')
res.send('Hello from B!')
})
最佳答案
当您已经有一个您可能打算在多个地方使用的先前定义的函数时,更有可能使用多个函数。例如:
app.get("/somePath", checkAuth, function(req, res) {
// you know it's already authenticated here
});
app.get("/someOtherPath", checkAuth, function(req, res) {
// you know it's already authenticated here
});
function checkAuth(req, res, next) {
if (some logic here) {
// allow handler chain to continue
next();
} else {
// auth error
res.status(401).end();
}
}
当然,您也可以使用中间件来检查身份验证,但上面的示例允许您使用可能在多个地方使用的一些中间件来定位一些特定的路由。
正如您已经观察到的,如果您不打算在其他任何地方使用该函数,那么您不妨将逻辑放入您的一个处理程序中。
关于javascript - 多个根处理程序的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46383729/