The express generator generates the following code in the app.js
page:
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
However, in the documentation, it says
Since path defaults to "/", middleware mounted without a path will be executed for every request to the app.
And gives this example:
// this middleware will not allow the request to go beyond it
app.use(function(req, res, next) {
res.send('Hello World');
})
// requests will never reach this route
app.get('/', function (req, res) {
res.send('Wele');
})
So, how could the 404
page ever be reached (or the /users
route for that matter) if nothing can get passed the app.use('/', routes)
line?
The express generator generates the following code in the app.js
page:
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
However, in the documentation, it says
Since path defaults to "/", middleware mounted without a path will be executed for every request to the app.
And gives this example:
// this middleware will not allow the request to go beyond it
app.use(function(req, res, next) {
res.send('Hello World');
})
// requests will never reach this route
app.get('/', function (req, res) {
res.send('Wele');
})
So, how could the 404
page ever be reached (or the /users
route for that matter) if nothing can get passed the app.use('/', routes)
line?
-
In the
routes
file, nonext()
is declared, so again, I would think that it would not "go any further" However going to/users
does indeed work. – Startec Commented Oct 23, 2014 at 8:33
1 Answer
Reset to default 15app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
Let's say your app.js has the above code (straight from the generator) and your server receives a request to /foo
. First, your app.use('/', routes);
middleware gets to check if it can handle the request, because it is defined first in your middleware stack. If the routes
object contains a handler for /foo
, and that handler calls res.send()
, then your server is done handling the request, and the rest of your middleware doesn't do anything. However, if the handler for /foo
calls next()
instead of res.send()
, or if the routes
object does not contain a handler for /foo
at all, then we continue going down the list of middleware.
The app.use('/users', users);
middleware does not execute, since the request is not to /users
or to /users/*
.
Finally, the 404 middleware executes last, since it was defined last. Since it was defined with no route, it executes for all requests that get past the first two middleware.