skip to Main Content

I am working on Nodejs and using "Express js", Right now i am working on "Router Middleware" function With following code,whenever i hit "http://localhost:3000" then "router middle" working/executed, but i want whenever i hit "http://localhost:3000/api/" (api route) only then "router middleware" should active/execute.Here is my current code

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

// Create a router instance
const router = express.Router();

// Define a middleware function specific to the router
const routerMiddleware = (req, res, next) => {
  // Perform some operations on the request or response
  console.log('Router middleware executed');
  next();
};

// Apply the middleware to the router
router.use(routerMiddleware);

// Define a route on the router
router.get('/example', (req, res) => {
  res.send('Hello from the router');
});

// Mount the router on the app
app.use('/api', router);

// Start the server
app.listen(3000, () => {
  console.log('Server started on port 3000');
});

2

Answers


  1. Instead of using router.use(routerMiddleware) you can add middleware directly to router like this: app.use('/api',routerMiddleware,router);

    Login or Signup to reply.
  2. The order where you apply middleware matters, if you don’t apply to middleware to some routes, define that routes before applying the middleware.

    In the following example, the /api/example route will not hit the middleware since it is before applying the middleware. But /api will hit.

    // Define a route on the router
    router.get('/example', (req, res) => {
        res.send('I will NOThit middleware');
    });
    
    // Apply the middleware to the router
    router.use(routerMiddleware);
    
    router.get('/', (req, res) => {
        res.send('I will hit the middleware');
    });
    
    // Mount the router on the app
    app.use('/api', router);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search