Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Express - app.all("*", func) doesn't get called when visiting root domain

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!

like image 875
pandringa Avatar asked Oct 10 '13 21:10

pandringa


2 Answers

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

like image 101
Plato Avatar answered Sep 21 '22 22:09

Plato


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
}));
like image 45
umbrel Avatar answered Sep 17 '22 22:09

umbrel