Getting Started With Node – Course

Installing and Configuring Middlewares

Middleware functions as name suggests can be used to make changes in the request/response lifecycle of the express. There are five types of middleware functions in the express.

  1. Application middleware
  2. Router middleware
  3. Error-handling middleware
  4. Built-in middleware
  5. Third-party middleware

Application middleware

We can use middleware in the application object of express.

For example:

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

app.use((req, res, next) => {
  console.log('Time:', Date.now());
  next();
});

app.listen(process.env.port || 3000);
console.log('Web Server is listening at port '+ (process.env.port || 3000));

Router middleware

In a similar way as application middleware, we can use router middleware.

For example:

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

router.use((req, res, next) => {
  console.log('Time:', Date.now());
  next();
});

router.get('/home', (req,res) => {
  // ------------
});

app.use('/', router);
app.listen(process.env.port || 3000);
console.log('Web Server is listening at port '+ (process.env.port || 3000));

Error-handling middleware

We can use this middleware to catch errors.

app.use(function (err, req, res, next) {
  res.status(500).send('Something broke!')
});

Learn more about this function here.

Built-in middleware

Express provides some middleware by default such as static, json etc.

Third-party middleware

We can use and third party middlewares such as body-parser. Here is how we can install third party middleware.

npm install body-parser

To use this middleware, we need to require it our code and load it.

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const router = express.Router();

router.get('/home', (req,res) => {
  res.send('<h2>Hello World, This is home router</h2>');
});


router.get('/profile', (req,res) => {
  res.send('<h2>Hello World, This is profile router</h2>');
});


router.get('/login', (req,res) => {
  res.send('<h2>Hello World, This is login router</h2>');
});


router.get('/logout', (req,res) => {
  res.send('<h2>Hello World, This is logout router</h2>');
});

app.use(bodyParser.json());
app.use('/', router);

app.listen(process.env.port || 3000);
console.log('Web Server is listening at port '+ (process.env.port || 3000));

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.