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

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

问题描述

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

Suppose you have a simple block of code like this:

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

这个函数有两个参数,reqres,分别代表请求和响应对象.

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.

路由中间件是一种更灵活、更强大的工具,但在我看来,因为它不依赖于特定的 URI 方案或路由排序.我倾向于对这样显示的示例进行建模,假设 Users 模型具有异步 findOne():

Route middleware 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!

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

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