Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript REST APIs with Express Create, Read, Update, Delete HTTP Status Codes

Nick Huemmer
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Nick Huemmer
Front End Web Development Techdegree Graduate 26,840 Points

Does Express now have a 404 handler built into it?

When following the video and just before building my single quote route with the 404 handler - I tested a request for a single route with an non-existent quote and I received a 404 status and message in basic HTML:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>

<body>
    <pre>Cannot GET /54231</pre>
</body>

</html>

I've noticed this in Express before when building a project- it seems that there is a native 404 handler built into Express now that may have been part of a recent update since this video was made. Could this be the case or am I missing something?

1 Answer

Yes, Express does have a default fallback error handler which executes after all declared middleware if needed. However, note that the default error handler responds with an HTML representation of the error when the course's API is designed to serve JSON. The browser is quite happy trying to render either, but for an application expecting JSON it would break the app if not caught so that some sort of JSON could be sent to the client instead.

I haven't yet concluded the course so perhaps Ms. Porth explains this later, but if one simply wants all errors to be delivered in the same JSON format one could always declare a single basic error-handler middleware (a four-argument callback sent to app.use()) at the end of the middleware function stack, declare all HTTP request callbacks with three arguments ((req, res, next)) and pass errors within prior requests to next().

Edit: Yup, she covers this in the next course.