Sobes.tech
Junior — Middle

How does Express.js manage incoming request processing?

sobes.tech AI

Answer from AI

Express.js manages incoming HTTP requests using a middleware mechanism — functions that are called sequentially upon receiving a request. Each middleware function can handle the request, modify the request or response object, perform logic, and pass control to the next function via calling next().

This approach allows building chains of request processing, where each part is responsible for its task: authentication, request body parsing, routing, error handling, etc.

Example of simple middleware in Express.js:

const express = require('express');
const app = express();

// Middleware for logging
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next(); // pass control to the next handler
});

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000);
How does Express.js manage incoming request… - sobes.tech