Middleware

In Express.js, middleware refers to functions that have access to the request object (req
), response object (res
), and the next
function in the application's request-response cycle. Middleware functions can perform a variety of tasks, such as
Modifying the request or response objects.
Ending the request-response cycle.
Calling the next middleware function in the stack.
Try running this code and see if the logs comes or not.
app.use(function(req, res, next) {
console.log("request received");
next();
})
app.get("/sum", function(req, res) {
const a = parseInt(req.query.a);
const b = parseInt(req.query.b);
res.json({
ans: a + b
})
});
Modifying the request
app.use(function(req, res, next) {
req.name = "harkirat"
next();
})
app.get("/sum", function(req, res) {
console.log(req.name);
const a = parseInt(req.query.a);
const b = parseInt(req.query.b);
res.json({
ans: a + b
})
});
Ending the request/response cycle
app.use(function(req, res, next) {
res.json({
message: "You are not allowed"
})
})
app.get("/sum", function(req, res) {
console.log(req.name);
const a = parseInt(req.query.a);
const b = parseInt(req.query.b);
res.json({
ans: a + b
})
});
Calling the next middleware function in the stack.
app.use(function(req, res, next) {
console.log("request received");
next();
})
app.get("/sum", function(req, res) {
const a = parseInt(req.query.a);
const b = parseInt(req.query.b);
res.json({
ans: a + b
})
});
Route specific middlewares
Route-specific middleware in Express.js refers to middleware functions that are applied only to specific routes or route groups, rather than being used globally across the entire application
const express = require('express');
const app = express();
// Middleware function
function logRequest(req, res, next) {
console.log(`Request made to: ${req.url}`);
next();
}
// Apply middleware to a specific route
app.get('/special', logRequest, (req, res) => {
res.send('This route uses route-specific middleware!');
});
app.get("/sum", function(req, res) {
console.log(req.name);
const a = parseInt(req.query.a);
const b = parseInt(req.query.b);
res.json({
ans: a + b
})
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Commonly used middlewares:
Through your journey of writing express servers
, you’ll find some commonly available (on npm) middlewares that you might want to use
1. express.json
The express.json()
middleware is a built-in middleware function in Express.js used to parse incoming request bodies that are formatted as JSON. This middleware is essential for handling JSON payloads sent by clients in POST or PUT requests.
const express = require('express');
const app = express();
// Use express.json() middleware to parse JSON bodies
app.use(express.json());
// Define a POST route to handle JSON data
app.post('/data', (req, res) => {
// Access the parsed JSON data from req.body
const data = req.body;
console.log('Received data:', data);
// Send a response
res.send('Data received');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
cors - Cross origin resource sharing
Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers that controls how resources on a web server can be requested from another domain. It's a crucial mechanism for managing cross-origin
requests and ensuring secure interactions between different origins
on the web.
Cross origin request from the browser
Same request from Postman
Subscribe to my newsletter
Read articles from Neha Sawant directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
