什么是参数“下一个”用于快递? [英] What is the parameter "next" used for in Express?

查看:74
本文介绍了什么是参数“下一个”用于快递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个简单的代码块:

Suppose you have a simple block of code like this:

app.get('/', function(req, res){
    res.send('Hello World');
});

此函数有两个参数, req res ,分别代表请求和响应对象。

This function has two parameters, req and res, which represent the request and response objects respectively.

另一方面,还有其他功能第三个参数称为 next 。例如,让我们看看下面的代码:

On the other hand, there are other functions with a third parameter called next. For example, lets have a look at the following code:

app.get('/users/:id?', function(req, res, next){ // Why do we need next?
    var id = req.params.id;
    if (id) {
        // do something
    } else {
        next(); // What is this doing?
    }
});

我不明白 next()是或为什么被使用。在这个例子中,如果id不存在,那么 next 实际在做什么?

I can't understand what the point of next() is or why its being used. In that example, if id doesn't exist, what is next actually doing?

推荐答案

它将控件传递给下一个匹配路由。例如,在给出的示例中,如果给出了 id ,则可以在数据库中查找用户,并将其分配给 req.user

It passes control to the next matching route. In the example you give, for instance, you might look up the user in the database if an id was given, and assign it to req.user.

以下可以使用以下路线:

Below, you could have a route like:

app.get('/users', function(req, res) {
  // check for and maybe do something with req.user
});

由于/ users / 123将匹配您的示例中的路由,首先会检查并查找用户 123 ;那么 / users 可以做到这一点。

Since /users/123 will match the route in your example first, that will first check and find user 123; then /users can do something with the result of that.

路由中间件(注意:链接是2.x文档,但是这是在3.x上测试的)更多灵活而强大的工具,但在我看来,由于它不依赖于特定的URI方案或路由排序。假设一个用户模型与async findOne(),我将倾向于模拟示例:

Route middleware (note: link is to 2.x documentation, but this is tested as working on 3.x) is a more flexible and powerful tool, though, in my opinion, since it doesn't rely on a particular URI scheme or route ordering. I'd be inclined to model the example shown like this, assuming a Users model with an async findOne():

function loadUser(req, res, next) {
  if (req.params.userId) {
    Users.findOne({ id: req.params.userId }, function(err, user) {
      if (err) {
        next(new Error("Couldn't find user: " + err));
        return;
      }

      req.user = user;
      next();
    });
  } else {
    next();
  }
}

// ...

app.get('/user/:userId', loadUser, function(req, res) {
  // do something with req.user
});

app.get('/users/:userId?', loadUser, function(req, res) {
  // if req.user was set, it's because userId was specified (and we found the user).
});

// Pretend there's a "loadItem()" which operates similarly, but with itemId.
app.get('/item/:itemId/addTo/:userId', loadItem, loadUser, function(req, res) {
  req.user.items.append(req.item.name);
});

能够控制这样的流量非常方便。您可能希望只有具有管理员标记的用户可以使用某些页面:

Being able to control flow like this is pretty handy. You might want to have certain pages only be available to users with an admin flag:

/**
 * Only allows the page to be accessed if the user is an admin.
 * Requires use of `loadUser` middleware.
 */
function requireAdmin(req, res, next) {
  if (!req.user || !req.user.admin) {
    next(new Error("Permission denied."));
    return;
  }

  next();
}

app.get('/top/secret', loadUser, requireAdmin, function(req, res) {
  res.send('blahblahblah');
});

希望这给了你一些灵感!

Hope this gave you some inspiration!

这篇关于什么是参数“下一个”用于快递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆