Skip to main content

Express.js

Middleware in Express.js

Express.js is a routing and Middleware framework for handling the different routing of the webpage and it works between the request and response cycle. Middleware gets executed after the server receives the request and before the controller actions send the response. Middleware has the access to the request object, responses object, and next, it can process the request before the server send a response. An Express-based application is a series of middleware function calls.

5 Express Middleware Libraries Every Developer Should Know

Some middlewares provided by express.js

  • Cookie-parser (Cookie-parser is a middleware that transfers cookies with client requests.)

  • Passport (Passport is a simple unrobustive authentication middleware for Node.js.) Facebook, twitter etc..

  • Morgan (Morgan is an HTTP request logger middleware for Node.js typically used for Express apps.)

  • CORS (CORS is a node.js package that provides a Connect/Express middleware for enabling CORS with a variety of options.)

//  Enable All CORS Requests
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors())

// OR
// Enable CORS for a Single Route
app.get('/', cors(), (req, res) => {
res.json({
message: 'Happy Coding'
});
});

Middleware explaination

Middleware Source: Middleware in Express.js

app.get(
"/",
// ========== Start of middleware ==========
(req, res, next) => {
console.log("hello");
next(); // It is responsible for calling the next middleware function if there is one.
},
// ========== End of middleware ==========
(req, res) => {
res.send(`<div>
<h2>Welcome to GeeksforGeeks</h2>
<h5>Tutorial on Middleware</h5>
</div>`);
}
);

Middleware-result Source: Middleware in Express.js