表达下一个功能,它是什么? [英] Express next function, what is it really for?

查看:102
本文介绍了表达下一个功能,它是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一直在尝试找到对 next()方法的一个很好的描述。在Express文档中,它表示 next('route')可用于跳转到该路由并跳过中间的所有路由,但有时 next没有参数调用任何人都知道一个很好的教程等,描述 next 函数?

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?

推荐答案

next()没有参数说只是开玩笑,我不是想要处理这个。它会重新进入并尝试找到匹配的下一条路线。

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.

这很有用,说如果你想拥有一些页面管理器与url slugs,as很多其他的东西,但这里是一个例子。

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() {
  //...
});

组成的代码应该检查数据库中是否存在具有特定ID段的页面。如果它发现一个渲染它!如果没有找到一个然后忽略此路由处理程序并检查其他的。

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.

所以 next()没有参数允许假装你没有处理路线,所以别的东西可以拿起来。

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

app.all('*')的命中计数器。这允许您执行一些共享的设置代码,然后移动到其他路由以执行更具体的操作。

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() {
  //...
});

这篇关于表达下一个功能,它是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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