Q
Q
quex2014-02-18 15:40:14
Node.js
quex, 2014-02-18 15:40:14

What is causing the strange behavior of express.use() in Node JS?

app.use(function(req,res,next){ console.log('middleware executed'); next(); });
app.get('/1',function(req,res){ console.log('/1'); res.end(); });
app.get('/2',function(req,res){ console.log('/2'); res.end(); });

Works as it should. when requesting pages /1 and /2, the middleware is executed in both cases.
Changing the order:
app.get('/1',function(req,res){ console.log('/1'); res.end(); });
app.use(function(req,res,next){ console.log('middleware executed'); next(); });
app.get('/2',function(req,res){ console.log('/2'); res.end();});

Middleware stops working at all, i.e. even when requesting a page /2
What could be the matter?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Keith, 2014-02-18
@quex

`use` must be used before the router. From the second example, when you register `/1` the express:application:L409 router is created . And when `/2` is registered, the path is added to the already existing router that comes before `use`.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question