Express Router makes your life easier

Yu Che Liu
2 min readFeb 5, 2021
Photo by Glenn Carstens-Peters on Unsplash

What is express.Router class?

We can use the Router class to create a modular and mountable route handler. When we create a Router instance to define other middleware or mounts the router module to the application.

Below is an example to create a Router instance:

var router = express.Router()

router.get(‘/’, function (req, res) {

res.send(‘ Hello Express’);

})

To mount the other router module, we can use the require keyword:

var app = require(‘./expressWeb’)

app.use(‘/expressWeb’, app)

When the user access the route: http://localhost/express. It will go to expressWeb file to look for the default router.

Writing middleware for use in Express apps.

What is Middleware?

In the Express framework, Middleware functions can call the multiple middlewares in the stack. To achieve this result, we can use the Middleware function that can access the request object and response object. If we need a chain of the request, we can use the next function to invoke another middleware function.

What can Middleware solve?

Middleware functions can solve the following question:

It can execute any code before it returns the response object to the user.

It can add extra value to the request and response object.

It can create a chain of middleware to execute the code.

The middleware structure looks like below:

app.get(‘/’, function(req, res, next){

Next();

})

Example:

Const Logger = function (req, res, next){

Console.log(‘Logged time: ’+ Date.now);

Next();

}

app.use(Logger)

Expatiation:

When the user enters a URL like http://localhost/ . It will execute the Logger function to log the existing time to the console. And Next function will go to look for the other middleware.

--

--

Yu Che Liu

Java Full stack developer | Google Android Associate developer certified | CompTIA Linux + certified | Teaching Assistant | https://www.linkedin.com/in/yucheliu