Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 511
Startec Avatar asked Oct 23 '14 08:10

Startec


People also ask

How does express JS handle 404?

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).

How does routing work in Express JS?

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.

What does Express router return?

Return Value: This function returns the New Router Object.


1 Answers

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.

like image 104
Raphael Serota Avatar answered Nov 15 '22 19:11

Raphael Serota