javascript - How does the Express.js 4 Router let things reach the 404 page -



javascript - How does the Express.js 4 Router let things reach the 404 page -

the express generator generates next code in app.js page:

app.use('/', routes); app.use('/users', users); // grab 404 , forwards error handler app.use(function(req, res, next) { var err = new error('not found'); err.status = 404; next(err); });

however, in documentation, says

since path defaults "/", middleware mounted without path executed every request app.

and gives example:

// middleware not allow request go beyond app.use(function(req, res, next) { res.send('hello world'); }) // requests never reach route app.get('/', function (req, res) { res.send('welcome'); })

so, how 404 page ever reached (or /users route matter) if nil can passed app.use('/', routes) line?

app.use('/', routes); app.use('/users', users); // grab 404 , forwards error handler app.use(function(req, res, next) { var err = new error('not found'); err.status = 404; next(err); });

let's app.js has above code (straight generator) , server receives request /foo. first, app.use('/', routes); middleware gets check if can handle request, because defined first in middleware stack. if routes object contains handler /foo, , handler calls res.send(), server done handling request, , rest of middleware doesn't anything. however, if handler /foo calls next() instead of res.send(), or if routes object not contain handler /foo @ all, go on going downwards list of middleware.

the app.use('/users', users); middleware not execute, since request not /users or /users/*.

finally, 404 middleware executes last, since defined last. since defined no route, executes requests past first 2 middleware.

javascript node.js express

Comments

Popular posts from this blog

assembly - What is the addressing mode for ld, add, and rjmp instructions? -

vowpalwabbit - Interpreting Vowpal Wabbit results: Why are some lines appended by "h"? -

Is there a way to convert an HTML page styled with Bootstrap CSS into email-compatible html? -