使用Express对带前缀的参数进行分解 [英] Factorize a prefixed parameter with Express

查看:437
本文介绍了使用Express对带前缀的参数进行分解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Express路由器有几条路线:

I've got several routes for my Express router:

router
.post('/:id/foo/*', func1)
.get('/:id/bar/*', func2)
.post('/:id/foobar/*', func3);

所有这些路线共享/:id /前缀,我想知道是否有写一个更紧凑和优雅的方式。

All those routes share the "/:id/" prefix and I would like to know if there is a more compact and elegant way for writing this.

目标是写下这样的东西:

The goal would be to write something like:

router
<something to capture de /:id/ and pass the subroutes to the following functions>
.post('/foo/*', func1)
.get('/bar/*', func2)
.post('/foobar/*', func3)

是错误/好/可行的想法?

Is a wrong/good/feasible idea?

推荐答案

在Express 4.5+中,您可以使用 路由器

In Express 4.5+ you could use a Router:

// mergeParams allows parent params to be passed down to child routes
var router = express.Router({
  mergeParams: true
});

router
  .post('/foo/*', func1)
  .get('/bar/*', func2)
  .post('/foobar/*', func3);

// Mount router at `/:id`
app.use('/:id', router);

您还可以使用 app.param 如果你想预处理 id 在其他中间件之前的param也会否定将父节点与子节点合并的需要。

You can also use app.param if you wanted to preprocess the id param before the other middleware which would also negate the need to merge the params from parent to child.

// No need to mergeParams as `res.locals.id` will be populated
//  by app.param middleware
var router = express.Router();
router
  .post('/foo/*', func1)
  .get('/bar/*', func2)
  .post('/foobar/*', func3);

app.param('id', function(req, res, next, id) {
  // ... do some logic if desired ...
  // assign the id to the res.locals object for downstream middleware
  res.locals.id = id;
  next();
});

app.use('/:id', router);

这篇关于使用Express对带前缀的参数进行分解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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