DR01D
DR01D

Reputation: 1365

How to make middleware respond on every request

I'm testing middleware in express and I ran into a problem.

On my second line I use app.use to call testOne and testTwo. When I visit my root / in a browser both of these middleware functions run. However if I visit a random static file for example image.png or about.htm they don't fire off. How do I make them fire off no matter what file I request? Thanks so much for any help!

app.use(express.static(path.join(__dirname, 'public')));

app.use(testOne, testTwo);

function testOne(request, response, next) {
    console.log('testOne ran');
}

function testTwo(request, response, next) {
    console.log('testTwo ran');
}

app.get('/', function(request, response) {
    response.sendFile(path.join(__dirname, 'public/index.htm'));
});

Upvotes: 1

Views: 1020

Answers (1)

jfriend00
jfriend00

Reputation: 707158

All middleware has to call next() in order to continue routing onto the next route handler.

app.use(testOne, testTwo);

function testOne(request, response, next) {
    console.log('testOne ran');
    next();
}

function testTwo(request, response, next) {
    console.log('testTwo ran');
    next();
}

app.use(express.static(path.join(__dirname, 'public')));

If you don't call next() the route just gets stalled and does nothing else (until it probably eventually times out).


Also, if you want these middleware to fire on all requests, then you need to put them first before other request handlers that might actually handle the request such as express.static().

Upvotes: 1

Related Questions