Express.js动态路由

时间:2016-02-17 06:51:20

标签: node.js express routes

我试图使用Node.js和Express.js创建小型CMS,我想知道动态路由模块的最佳方法是什么。我可以理解一些红色文件,有些我无法理解。什么是正确的方法呢?

如果用户(通常是站点管理员)创建静态页面,论坛和一些名称相同的模块:

  • staticPage
  • QnAforum
  • andAnythingUserNamed

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

首先:我认为这是理智的方式,网址很干净,但可能会降低网页加载速度。

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

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

});

第二:如果我将模块用户分开,我认为网址更复杂,但网站加载比上面的方式更快。

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,并快速加载两者?

2 个答案:

答案 0 :(得分:2)

首先定义所有静态路由:

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(...........);
    });
});

答案 1 :(得分:0)

您可以通过首先定义所有“静态”路由,然后使用动态路由器来完善您的第一种方法,如下所示:

app.get('/login', function (req, res) { /* ... */ });

app.get('/logout', function (req, res) { /* ... */ });

app.get('/:dynamicRoute', function (req, res) { 
  res.send(res.params.dynamicRoute);
});
相关问题