gpt4 book ai didi

node.js - Express.js 动态路由

转载 作者:太空宇宙 更新时间:2023-11-03 23:33:29 25 4
gpt4 key购买 nike

我正在尝试使用 Node.js 和 Express.js 制作小型 CMS,我想知道动态路由模块的最佳方法是什么。我红色记录了一些我能理解的,还有一些我无法理解的。正确的做法是什么?

如果用户(通常是站点管理员)制作静态页面、论坛和某些模块的名称全部不同:

  • 静态页面
  • QnAforum
  • andAnythingUserNamed

我认为有两种方法可以路由此页面,

首先:我认为这是明智的方式,并且 URL 很干净,但可能会降低页面加载速度。

app.get(/:module, function(req, res, next){
...

// if req.params.modules == (login || logout ...)
// handle it
// else if
// module.find()... and render...

});

第二:如果我将用户制作的模块分开,我认为 URL 会更复杂,但它比上述方式加载速度更快。

app.get(/forum/:id, function(req, res, next){
...
// forum.find({forum_id: req.params.id})...

});

app.get(/staticPage/:id, function(req, res, next){
...
// staticPage.find({staticPage_id: req.params.id})...
});

是否有正确的方法来使用更清晰的 URL 并快速加载两者?

最佳答案

首先定义所有静态路由:

app.get(/forum/:id, function(req, res, next){
...
// forum.find({forum_id: req.params.id})...

});

现在,要为 CMS 创建静态页面,只需在路径 / 下创建自定义中间件,并在数据库中搜索请求路径以检查页面是否存在。

// page storage
// could be MySQL, MongoDb or anything else you are using
var pages = require(......);

app.use(function(req, res, next) {
// find page in the database using the request path
pages.findPage(req.path, funcion(err, page) {
// error occured, so we call express error handler
if (err) return next(err);

// no page exists, so call the next middleware
if (!page) return next();

// page found
// so render the page and return response
// return res.status(200).render(...........);
});
});

关于node.js - Express.js 动态路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35449790/

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