DEV Community

Rittwick Bhabak
Rittwick Bhabak

Posted on

Node.js Crash Course - Part 11 - Express Router and MVC

1. Using express router to make app.js clutter free

app.get('/', (req, res) => { ...
app.get('/about', (req, res) => { ...
app.get('/blogs', (req, res) => { ...
app.post('/blogs', (req, res) => { ...
app.delete('/blogs/:id', (req, res) => { ...
app.get('/blogs/:id', (req, res) => { ...
app.use((req, res) => { ...
Enter fullscreen mode Exit fullscreen mode

There are 5 routes with prefix /blog. We can move it to another to make app.js clutter free.

/routes/blogRouter.js:

const express = require('express');
const router = express.Router();
const Blog = require('../models/blog');

router.get('/', (req, res) => {...
router.post('/', (req, res) => {...
router.delete('/:id', (req, res) => {...
router.get('/create', (req, res) => {...
router.get('/:id', (req, res) => {...

module.exports = router
Enter fullscreen mode Exit fullscreen mode

and the app.js

const blogRouter = require('./routes/blogRouter');
app.get('/', (req, res) => {...
app.get('/about', (req, res) => {...
app.use('/blogs', blogRouter)
app.use((req, res)=>{...
Enter fullscreen mode Exit fullscreen mode

2. MVC - Model, View, Controller

We've already seen models, and views.

Controller is , moving the functions which communicate with models to an another folder generally called 'controllers'.
/controllers/blogController.js

const blog_index = (req, res) => {
    Blog.find().sort({ createdAt: -1})
        .then( results => {
            res.render('blogs/index', { title: 'Home', blogs: results });
        })
        .catch( err => {
            res.render('blogs/index', { title: 'Home', blogs: [] });
        })
}
Enter fullscreen mode Exit fullscreen mode

and using this blog_index function from blogRouter.js

router.get('/', blogController.blog_index);
Enter fullscreen mode Exit fullscreen mode

Useful naming convention example is:
blog_index, blog_details, blog_delete, blog_create_get, blog_create_post

Top comments (0)