What is a Middleware?:
According to wikiperdia,
Middleware is a type of computer software that provides services to software applications beyond those available from the operating system. It can be described as "software glue".
In our case, express js middleware is a functionality that runs between a request to the server and the response from the server.
Types of Express Middleware:
- Built-in Middleware:
- express.static: serves static assets such as HTML files, images, and so on.
- express.json: parses incoming requests with JSON payloads.
- express.urlencoded: parses incoming requests with URL-encoded payloads.
- Third Party Middleware:
Middleware installed via npm
- Custom Middleware:
Created by you - the developer - for a project.
How To Apply Middleware?:
- Application or Route Level:
const express = require('express');
//Start express app.
const app = expree();
//Apply a single middleware
app.use(middleware);
//Apply multiple middleware
app.use(middleware1, middleware2);
//Or via an array
const middlewareArr = [middleware1, middleware2];
app.use(middlewareArr);
- Endpoint Level:
//Apply a single middleware
app.get('/', middleware, (res, req) => {};
//Apply multiple middleware
app.get('/', middleware1, middleware2, (res, req) => {};
//Or via an array
const middlewareArr = [middleware1, middleware2];
app.get('/', middlewareArr, (res, req) => {};
Top comments (2)
@islam It would be nice if you put this as a simple Node project. Use the middleware for says
logging
orauthentication
and put the code on github.Hi @vishalraj82
I just wanted to explain the concept in a minimal way.
But I think you are right also because people want to see code examples.
Thank you