2015年8月27日 星期四

express node req res next()

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

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

      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);
});

沒有留言:

張貼留言