Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js dynamic routes

I'm trying to make tiny CMS using Node.js and Express.js, I wonder what is the best way to routes the module dynamically. I red documents some I could understand, and some I couldn't understand. What is a proper way to do it?

If a user(usually site administrator) make a static pages, forums, and some modules named all different :

  • staticPage
  • QnAforum
  • andAnythingUserNamed

I think two way to routes this page,

First : I think it is sane way, and URL is clean, but possible to decrease page loading speed.

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

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

});

Second : If I separate module user made, I think the URL is more complicated, but it is faster site loading than above way.

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

Is there a proper way to using cleaner URL, and fast loading both?

like image 472
ton1 Avatar asked Nov 20 '25 11:11

ton1


2 Answers

First define all the static routes:

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

});

Now, to create static pages for a CMS, just create a custom middleware under the path / and search the request path in the database to check if a page exists.

// 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(...........);
    });
});
like image 166
Ujjwal Ojha Avatar answered Nov 23 '25 01:11

Ujjwal Ojha


You can refine your first approach by defining all the 'static' routes first, and then following with your dynamic router, like this:

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

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

app.get('/:dynamicRoute', function (req, res) { 
  res.send(res.params.dynamicRoute);
});
like image 29
lxe Avatar answered Nov 23 '25 01:11

lxe