Using Express and Express Router. I've got a handful of files in a single directory that all implement Express.Router
. I'm dynamically requiring them, adding some middleware and then attached them to a "meta" router and finally calling app.use("/",MetaRouter)
.
My problem is that the middleware is getting called multiple times for each route.
Here is /index.js
:
const express = require('express')
const bodyParser = require('body-parser');
const app = express();
const port = 4000;
var cors = require('cors')
var routes = require('./routes');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(routes);
app.listen(port, '0.0.0.0', () => console.log(`Example app listening on port ${port}!`))
Which requires /routes/index.js
:
const fs = require('fs');
const path = require('path');
var express = require('express');
var MetaRouter = express.Router();
var passport = require('passport');
const files = fs.readdirSync(__dirname).filter(file => file !== 'index.js');
const fileModules = {};
var middleware = function(req, res, next) {
console.log('In The Middleware');
next();
}
files.forEach(file => {
const { name } = path.parse(file);
fileModules[name] = require(`./${name}`);
});
Object.entries(fileModules).forEach(([key, _router]) => {
_router.use(middleware);
MetaRouter.use(_router);
});
module.exports = MetaRouter;
And here is an example of one of the router files in the directory:
const BoxRequestService = require("../services/request/box_request_service.js");
var express = require('express');
var router = express.Router();
router.get('/box',
async function (req, res) {
res.json(await BoxRequestService.getAll(req, res));
});
router.get('/box/:id',
async function (req, res) {
res.json(await BoxRequestService.findById(req, res));
}
);
router.put('/box/:id',
async function (req, res) {
res.json(await BoxRequestService.update(req, res));
});
router.post('/box', async function (req, res) {
res.json(await BoxRequestService.create(req, res));
});
module.exports = router;
Expected Results
So when requesting http://localhost/box, I expect to see "In The Middleware" in the console exactly once.
Actual Results
Instead, I see "In The Middleware" logged multiple times. It also depends on the order in which the files are required. So given this list of files (required in this order):
- /routes/A.js
- /routes/B.js
- /routes/C.js
- /routes/D.js
If a route in A.js
is requested, the middleware is called once.
If a route in B.js
is requested, the middleware is called twice.
If a route in C.js
is requested, the middleware is called three times.
etc.
etc.