Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 用Express分解前缀参数_Javascript_Node.js_Express - Fatal编程技术网

Javascript 用Express分解前缀参数

Javascript 用Express分解前缀参数,javascript,node.js,express,Javascript,Node.js,Express,我的快速路由器有几条线路: router .post('/:id/foo/*', func1) .get('/:id/bar/*', func2) .post('/:id/foobar/*', func3); 所有这些路由都使用“/:id/”前缀,我想知道是否有一种更简洁、更优雅的方式来写这篇文章 我们的目标是写出如下内容: router <something to capture de /:id/ and pass the subroutes to the following func

我的快速路由器有几条线路:

router
.post('/:id/foo/*', func1)
.get('/:id/bar/*', func2)
.post('/:id/foobar/*', func3);
所有这些路由都使用“/:id/”前缀,我想知道是否有一种更简洁、更优雅的方式来写这篇文章

我们的目标是写出如下内容:

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

是一个错误的/好的/可行的想法吗?

在Express 4.5+中,您可以使用:

如果您想在其他中间件之前预处理
id
param,也可以使用,这样就不需要将参数从父级合并到子级

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

你想优化它的原因是什么?为了不重复我自己我不知道语言的细节,但你能做一些类似的事情:
.post(“/:id/[foo | bar | foobar]”,func)
?这需要维护一个“dispatcher”函数。我想我更喜欢在每条路线中重复“/:id/”。
// 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);