Mark As Completed Discussion

Middleware in Express

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle. These functions can execute any code, make changes to the request and response objects, and end the request-response cycle by sending a response or passing control to the next middleware function.

Using Middleware in Express

To use middleware in an Express.js application, you can use the app.use() method to mount the middleware function. This function will be executed for every request that is sent to the server.

For example, let's create a simple middleware function that logs the timestamp, request method, and URL for every incoming request:

JAVASCRIPT
1// Create an Express application
2const app = express();
3
4// Define a middleware function
5const logger = (req, res, next) => {
6  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
7  next();
8};
9
10// Use the middleware function
11app.use(logger);
12
13// Define routes
14app.get('/', (req, res) => {
15  res.send('Hello, World!');
16});
17
18// Start the server
19app.listen(3000, () => {
20  console.log('Server started on port 3000');
21});

In this example, we create an Express application and define a middleware function called logger. The function logs the timestamp, request method, and URL for each incoming request. We use app.use() to mount the logger middleware function to our application, and then define a route for the root URL ('/') that sends a simple response.

By using middleware in our Express.js application, we can perform various tasks such as logging, authentication, error handling, and more. Middleware allows us to modularize our code and ensure that each request goes through the necessary processing before reaching the final route.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment