javascript - 多个根处理程序的目的是什么?

标签 javascript express routes

如前所述,可以提供多个回调函数,并像中间件一样处理请求。它们可以采用函数、函数数组或两者组合的形式,如以下示例所示。

例如:

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/

相关文章:

node.js - 无法使用express3加载我的文件

ruby-on-rails - @rails_folks | '' http ://twitter. com/#!/user/followers"| 请解释

javascript - 语法错误 : expected expression, 在 AngularJS 路由刷新时得到 '<'

javascript - angular.equals() 占用了 50% 的执行时间

javascript - 水平下拉菜单鼠标悬停问题

javascript - 使用 MailGun 从 Node.JS 发送 HTML 电子邮件

ios 导航与苹果或谷歌地图与多个目标

javascript - 对齐 self :flex start is not sending child element to the top

javascript - 如何在 AngularJS 应用程序中支持用户可选择的区域设置

javascript - 当我添加新的中间件来处理express.js中的路径时,404未找到