- Let's create a basic example with custom middleware in an Express.js application.
- Project Structure: Create a project structure with the following directories and files:
    - my-express-app/
        - middlewares/
            - myMiddleware.js
        - routes/
            - index.js
        - app.js
        - package.json
- Middleware File (`myMiddleware.js`): Create a custom middleware file in the `middlewares` directory:
    // middlewares/myMiddleware.js
    const myMiddleware = (req, res, next) => {
        console.log('Custom Middleware executed!');
        next(); // Call the next middleware in the stack
    };
    module.exports = myMiddleware;
- Route File (`index.js`): Create a route file in the `routes` directory:
    // routes/index.js
    const express = require('express');
    const router = express.Router();
    router.get('/', (req, res) => {
        res.send('Hello from the index route!');
    });
    module.exports = router;
- Express App (`app.js`): Set up the Express.js application:
    // app.js
    const express = require('express');
    const myMiddleware = require('./middlewares/myMiddleware');
    const indexRoute = require('./routes/index');
    const app = express();
    const PORT = 3000;
    // Use the custom middleware for all routes
    app.use(myMiddleware);
    // Use the index route
    app.use('/', indexRoute);
    app.listen(PORT, () => {
        console.log(`Server is running on http://localhost:${PORT}`);
    });
- Run the Application: Run your application using the command:
    node app.js
- Visit `http://localhost:3000` in your browser, and you should see the message "Hello from the index route!" in the console. The custom middleware `myMiddleware` is executed before the route handler, demonstrating the middleware's role in the request-response cycle.
- This example showcases a basic Express.js application with custom middleware. The custom middleware logs a message to the console and then calls the next middleware in the stack, which is the route handler. Middleware functions provide a powerful mechanism for handling various tasks during the processing of incoming requests.
No comments:
Post a Comment