Express next 函数,到底是干什么用的? [英] Express next function, what is it really for?

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

问题描述

一直试图找到对 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 slug 的页面管理器以及许多其他东西,但这里有一个示例.

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 slug 的页面.如果它找到一个渲染它!如果没有找到,则忽略此路由处理程序并检查其他路由处理程序.

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

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

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