Node.js Middleware

Middleware in Express is a function that executes during the request-response cycle. It can modify the request, response, or terminate the request-response cycle.

1. Basic Middleware

Here's how you can create a basic middleware in Express:

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

// Simple middleware function
app.use((req, res, next) => {
    console.log('Middleware executed');
    next();  // Passes the request to the next middleware or route handler
});

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

app.listen(3000, () => {
    console.log('Server is running on http://localhost:3000');
});

This middleware logs a message to the console each time a request is made to the server.

2. Middleware for Specific Routes

You can also apply middleware to specific routes:

app.use('/user', (req, res, next) => {
    console.log('Middleware for /user route');
    next();
});

app.get('/user', (req, res) => {
    res.send('User route');
});

This middleware will only be executed when accessing routes under `/user`.

3. Error Handling Middleware

Middleware can also handle errors. Here’s an example of an error-handling middleware:

app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Something went wrong!');
});

This middleware catches errors and responds with a message and status code 500.

4. Conclusion

Middleware is a powerful feature in Express that allows you to handle various tasks such as logging, authentication, and error handling. You can apply it globally or for specific routes depending on your needs.

0 Interaction
623 Views
Views
16 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home