Junior — Middle
Can you explain what is meant by Middleware in the context of Node.js and how it is used?
sobes.tech AI
Answer from AI
Middleware in Node.js are functions that have access to the request (req), response (res), and the next middleware function in the request-response cycle.
They are used to handle requests, perform intermediate actions (such as logging, authentication, parsing request body), and pass control to the next middleware.
In Express.js, middleware are declared as functions with three parameters: (req, res, next). Calling next() passes control to the next middleware.
Example of simple middleware in Express:
const express = require('express');
const app = express();
// Logging middleware
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // pass control to the next middleware
});
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(3000);