【发布时间】:2014-04-28 04:06:43
【问题描述】:
我正在使用 Node 和 Express 实现一个 RESTful API。说到路由,目前是这样的:
var cat = new CatModel();
var dog = new DogModel();
app.route('/cats').get(cat.index);
app.route('/cats/:id').get(cat.show).post(cat.new).put(cat.update);
app.route('/dogs').get(dog.index);
app.route('/dogs/:id').get(dog.show).post(dog.new).put(dog.update);
我不喜欢这个有两个原因:
- 无论我是否需要,都会实例化 cat 和 dog 模型。
- 我必须为每个路径模式重复 /cats 和 /dogs
我很想拥有这样的东西(当然不行):
app.route('/cats', function(req, res)
{
var cat = new CatModel();
this.route('/').get(cat.index);
this.route('/:id').get(cat.show).post(cat.new).put(cat.update);
});
app.route('/dogs', function(req, res)
{
var dog = new DogModel();
this.route('/').get(dog.index);
this.route('/:id').get(dog.show).post(dog.new).put(dog.update);
});
在没有任何其他模块的现代 Express 中是否有一种干净的方式(如 express-namespace)?我可以为每个型号选择单独的路由器,并为它们分配app.use('/cats', catRouter)。但是,如果我有多个层级,例如'/tools/hammers/:id',该怎么办?然后我会在路由器中的路由器中拥有路由器,这对我来说似乎有点过头了。
【问题讨论】:
标签: node.js routes url-routing