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('Welcome');
})
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?
All you need to do is add a middleware function at the very bottom of the stack (below all other functions) to handle a 404 response: app. use((req, res, next) => { res. status(404).
Routing refers to how an application's endpoints (URIs) respond to client requests. For an introduction to routing, see Basic routing. You define routing using methods of the Express app object that correspond to HTTP methods; for example, app.get() to handle GET requests and app.post to handle POST requests.
Return Value: This function returns the New Router Object.
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);
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With