22
EXPRESS JS 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.
- 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.
- 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) => {};
22