Routing

Express JS Basic Routing is done using basic http methods like GET, POST and so on. We have done basic routing in last article using GET and POST.

See Examples of basic routing

Express JS GET


const express=require("express");
const app=express();

app.get('/',(req,res)={
    console.log("get method);
    res.send('get');
});   
    

Express JS POST


const express=require("express");
const app=express();

app.post('/',(req,res)={
    console.log("post method);
    res.send('post');
});   
    

Express Router

Express JS use express.Router class to create modular and mountable route handlers. The Router instance also known as Mini-app, is a complete middleware routing system in ExpressJS.


const express=require("express");
const router=express.Router();


Router.get

Now we are using Router.use to add a middleware function. We will create two modules, one for admin and second for user.

Create admin route

    /* admin.js */

const express=require("express");
const router=express.Router();

router.get('/',(req,res)=>{
    console.log("hi admin");
    res.status(200).send("hi admin");
});

module.exports=router;

Run route in main app

    /* app.js */

const express=require('express');
const app=express();
const admin=require('./admin');

app.use('/admin',admin);

app.listen(3000)

hi admin

node src/app.js

Router Example

In the example below, we are using two different modules , admin and user.

Admin route

    /* admin.js */

const express=require("express");
const router=express.Router();

// middleware specific to admin
router.use(function timeLog (req, res, next) {
    console.log('Admin login at: ', Date.now())
    next()
});

router.get('/',(req,res)=>{
    console.log("hi admin");
    res.status(200).send("hi admin");
});

module.exports=router;

User route

    /* user.js */

const express=require('express');
const router=express.Router();

// middleware specific to user
router.use(function timeLog (req, res, next) {
    console.log('User login at: ', Date.now())
    next()
});

router.get('/',(req,res)=>{
    res.status(200).send("hi user");
});


module.exports=router;

Main App

    /* app.js */
const express=require('express');
const app=express();

const admin=require('./admin');
const user=require('./user');


app.use('/admin',admin);
app.use('/user',user);

app.listen(3000,()=>{ console.log('server running')})

Run App

server running

node src/app.js

Now lets open both admin and user pages one by one to see routing. Open a web browser and type following URLs one by one.

Admin login at: 1589455931358

127.0.0.1:3000/admin

User login at: 1589455932090

127.0.0.1:3000/user