gpt4 book ai didi

node.js - 使用普通 Express.js 的分层路由

转载 作者:搜寻专家 更新时间:2023-10-31 22:27:25 26 4
gpt4 key购买 nike

我正在使用 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);

我不喜欢这个有两个原因:

  1. 无论我是否需要,猫和狗模型都会被实例化。
  2. 我必须为每个路径模式重复/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' 怎么办?然后我会在路由器内的路由器内设置路由器,这对我来说似乎有点过分了。

最佳答案

I would then have routers within routers within routers, which seems like overkill to me.

也许吧,但这是内置的前缀方法 -- 到 app.use()一个Router() .

var cats = express.Router();
app.use('/cats', cats);

cats.route('/').get(cat.index);
cats.route('/:id').get(cat.show).post(cat.new).put(cat.update);

// ...

并且,拥有一个路由器 .use()另一个定义多个深度:

var tools = express.Router();
app.use('/tools', tools);

var hammers = express.Router();
tools.use('/hammers', hammers);

// effectively: '/tools/hammers/:id'
hammers.route('/:id').get(...);

不过,为了更接近您的第二个代码段,您可以定义一个自定义方法:

var express = require('express');

express.application.prefix = express.Router.prefix = function (path, configure) {
var router = express.Router();
this.use(path, router);
configure(router);
return router;
};

var app = express();

app.prefix('/cats', function (cats) {
cats.route('/').get(cat.index);
cats.route('/:id').get(cat.show).post(cat.new).put(cat.update);
});

app.prefix('/dogs', ...);

app.prefix('/tools', function (tools) {
tools.prefix('/hammers', function (hammers) {
hammers.route('/:id').get(...);
});
});

关于node.js - 使用普通 Express.js 的分层路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23332317/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com