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
Instead of using
router.use(routerMiddleware)
you can add middleware directly to router like this:app.use('/api',routerMiddleware,router);
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.