Handling different routes in express.js

Node.jsServer Side ProgrammingProgramming

For handling different routes, use() function is used. use() function has multiple overloaded version, one of version also takes url path as a argument. Based on the url path, the requests will be filtered out for respective middleware.

const http = require('http');
const express = require('express');
const app = express();
app.use('/', (req, res,next)=>{
   console.log('first middleware');
   res.send('<h1> first midleware:
   Hello Tutorials Point </h1>');
});
const server = http.createServer(app);
server.listen(3000);

in above example we used ‘/’ as url path, it’s a default.

Now, as every route starts with ‘/’, the above middleware executes for every http request. It works for ‘/’ and for ‘/username’ as well.

To avoid above problem , we will have to use path specific middleware first before default middleware.

const http = require('http');
const express = require('express');
const app = express();
app.use('/username', (req, res,next)=>{
   res.send('<h1> My username </h1>');
});
app.use('/', (req, res,next)=>{
   console.log('first middleware');
   res.send('<h1> first midleware: Hello Tutorials Point </h1>');
});
const server = http.createServer(app);
server.listen(3000);

Now, we used ‘/username’ path middleware first and as we have not used next() in the it , it will not pass the http request to next middleware.

So we see browser output like below for different urls −

localhost:3000

For localhost:3000/username

If any pre-processing on http request requires for all, the using default middleware url path ‘/’ can be useful. Just we will have to use next() in it to pass the request after pre-processing to next middlewares.

const http = require('http');
const express = require('express');
const app = express();
app.use('/', (req, res,next)=>{
   console.log('log request info', req);
   next();
});
app.use('/username', (req, res,next)=>{
   res.send('<h1> My username </h1>');
});
app.use('/', (req, res,next)=>{
   console.log('first middleware');
   res.send('<h1> first midleware: Hello Tutorials Point </h1>');
});
const server = http.createServer(app);
server.listen(3000);
raja
Published on 13-May-2020 16:49:50
Advertisements