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 :
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?
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(...........);
});
});
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With