자바스크립트 중간 실행 함수 (Middleware Functions)

In JavaScript, middleware functions are a powerful concept that allows you to modify or augment the behavior of a function before or after its actual execution. Middleware functions are widely used in frameworks like Express.js to handle HTTP requests and implement various features such as authentication, logging, error handling, etc.

What are Middleware Functions?

Middleware functions act as intermediaries between the incoming request and the final response. They are executed in a sequential manner, where each middleware function has the ability to modify the request, response, or even terminate the execution chain.

The primary purpose of middleware functions is to provide a reusable and modular approach to implement cross-cutting concerns in your application. These concerns can include authentication, input validation, error handling, data transformation, and many more.

Example Code

// Example of a simple middleware function
const loggerMiddleware = (req, res, next) => {
  console.log(`[${new Date().toLocaleString()}] ${req.method} ${req.url}`);
  next();
}

// Example usage of the middleware function

// Registering the middleware function
app.use(loggerMiddleware);

// Middleware function will be called before executing this route handler
app.get('/', (req, res) => {
  res.send('Hello World!');
});

In the above example, we define a loggerMiddleware function that takes in the req (request), res (response), and next parameters. Inside the function, we log the current time, HTTP method, and URL of the incoming request. We then call next() to pass control to the next middleware function in the chain.

We then register the loggerMiddleware using app.use() in an Express.js application. This means that the loggerMiddleware will be executed for every incoming request before reaching the route handler.

Benefits of Using Middleware Functions

Conclusion

Middleware functions are a fundamental concept in JavaScript, enabling you to modify and extend the behavior of your functions before or after execution. They are widely used in frameworks like Express.js to implement various features and handle cross-cutting concerns in web applications. By adopting middleware functions, you can achieve code reusability, modularity, and better control of your application’s flow.