Express next function, what is it really for? Ask Question

Express next function, what is it really for? Ask Question

Have been trying to find a good description of what the next() method does. In the Express documentation it says that next('route') can be used to jump to that route and skip all routes in between, but sometimes next is called without arguments. Anybody knows of a good tutorial etc that describes the next function?

ベストアンサー1

next() with no arguments says "just kidding, I don't actual want to handle this". It goes back in and tries to find the next route that would match.

This is useful, say if you want to have some kind of page manager with url slugs, as well as lots of other things, but here's an example.

app.get('/:pageslug', function(req, res, next){
  var page = db.findPage(req.params.pageslug);
  if (page) {
    res.send(page.body);
  } else {
    next();
  }
});

app.get('/other_routes', function() {
  //...
});

That made up code should check a database for a page with a certain id slug. If it finds one render it! if it doesn't find one then ignore this route handler and check for other ones.

So next() with no arguments allows to pretend you didn't handle the route so that something else can pick it up instead.


Or a hit counter with app.all('*'). Which allows you to execute some shared setup code and then move on to other routes to do something more specific.

app.all('*', function(req, res, next){
  myHitCounter.count += 1;
  next();
});

app.get('/other_routes', function() {
  //...
});

おすすめ記事