ReasonJun

Express.js : Middleware 본문

Backend/Express.js

Express.js : Middleware

ReasonJun 2023. 9. 4. 15:50
728x90

Middleware in Express.js is a function that is executed before the request is routed to a specific controller or action. Middleware can be used to perform any number of tasks, such as:

  • Logging the request and response.
  • Validating the request data.
  • Encrypting or decrypting the request data.
  • Caching the request data.
  • Generating a response.
  • And much more.

Middleware functions are chained together, and each middleware function has access to the request object, the response object, and the next middleware function in the chain. The next middleware function is commonly denoted by a variable named next.

Here is an example of a middleware function that logs the request and response:

const express = require('express');

const middleware = (req, res, next) => {
  console.log(`Request received: ${req.url}`);
  next();
};

const app = express();

app.use(middleware);

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

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

In this example, the middleware function logs the request URL to the console. The next() function tells Express to continue the middleware chain and execute the next middleware function.

Middleware can be used to add functionality to your Express application without having to modify the core code. This makes it a powerful tool for building flexible and extensible applications.

Here are some of the benefits of using middleware in Express.js:

  • Middleware can be used to add functionality to your application without having to modify the core code.
  • Middleware can be chained together, so you can easily add multiple layers of functionality.
  • Middleware is a powerful tool for building flexible and extensible applications.
728x90

'Backend > Express.js' 카테고리의 다른 글

Express.js : MVC Pattern  (0) 2023.09.04
Express.js : res.end() / res.send()  (0) 2023.09.04
Express.js : res.json() / res.send()  (0) 2023.09.04
Express.js : Concept  (0) 2023.09.04
Comments