【问题标题】:Express.js dynamic routesExpress.js 动态路由
【发布时间】:2016-05-28 17:58:57
【问题描述】:

我正在尝试使用 Node.js 和 Express.js 制作微型 CMS,我想知道动态路由模块的最佳方式是什么。我红了一些我能理解的文件,一些我看不懂的文件。什么是正确的方法?

如果一个用户(通常是网站管理员)制作一个静态页面、论坛和一些模块名称都不同:

  • 静态页面
  • QnA 论坛
  • 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 并快速加载两者?

【问题讨论】:

    标签: node.js express routes


    【解决方案1】:

    首先定义所有静态路由:

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

    【讨论】:

      【解决方案2】:

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

      app.get('/login', function (req, res) { /* ... */ });
      
      app.get('/logout', function (req, res) { /* ... */ });
      
      app.get('/:dynamicRoute', function (req, res) { 
        res.send(res.params.dynamicRoute);
      });
      

      【讨论】:

      • 如果我使用动态路由,那么我的 css 文件不会呈现!!!
      猜你喜欢
      • 1970-01-01
      • 2013-05-22
      • 2014-10-26
      • 2020-08-03
      • 1970-01-01
      • 2017-08-16
      • 2017-09-02
      • 2017-01-22
      相关资源
      最近更新 更多