I'm trying to set a global function that is called on every page load, regardless of its location in my website. As per Express's API, I've used
app.all("*", doSomething);
to call the function doSomething on every page load, but it doesn't completely work. The function fires on every page load, except for page loads of the base domain (e.g. http://domain.com/pageA will call the function, but http://domain.com won't). Does anyone know what I'm doing wrong?
Thanks!
I bet that you placed
app.get('/', fn)
above
app.all("*", doSomething);
Remember that Express will execute middleware functions in the order they are registered until something sends a response
I know that's an old one, but still maybe useful to someone.
I think the problem could be:
app.use(express.static(path.join(__dirname, 'public')));
var router = express.Router();
router.use(function (req, res, next) {
console.log("middleware");
next();
});
router.get('/', function(req, res) {
console.log('root');
});
router.get('/anything', function(req, res) {
console.log('any other path');
});
where is middleware invoked on any path, but /
It happens because express.static by default serves public/index.html
on /
To solve it add parameter to the static middleware:
app.use(express.static(path.join(__dirname, 'public'), {
index: false
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With