NodeJS API-Part 3 / Returning 404 not found

Soon Sam Santos
2 min readJan 17, 2021

This is the 3º tutorial of a complete series of building a production NodeJS API using Express, MySQL and Sequelize”.

Full source code of this class is available at GitHub Martial Arts API Part 3

Photo by Eerik Sandstrom on Unsplash

UNDERSTANDING THE PROBLEM

As you could see in the past tutorials, if you type localhost:8000/dojos you will get a JSON Object with one dojo (gym).

But if you type localhost:8000/ , localhost:8000/students or any other endpoint you will not get a meaningfull response.

It would be good to send Not Found to the user in case he typed something we do not support, for that we are going to use Express MiddleWares.

As everything in this tutorial, it will be really easy and quick.

ADD NOT FOUND MIDDLEWARE

This is pretty simple, instead of app.get() we will be using app.use() , this means that we are using this rule in any situation that gets in there.

First our application will try to get /dojos , in case the user typed something different as /students it will go to the next rule and it will find our app.use() .

Any request that reach there it means we didn’t find anything that match and we will return Not Found .

Then, we just create an error, set it status to 404 and send the response in JSON format.

NOTE: Try to move your app.use() before your app.get() and you will see that it will give Not Found for every single request, including /dojos . Because the code runs from top to bottom and it will always run not found first. Therefore, this code should be at the end of your app.

CONCLUSION

Alright, with pretty much no code we can already see our application. This is the power of NodeJS. Let’s keep going to add our structure and connect to the database.

Full source code of this class is available at GitHub Martial Arts API Part 3

--

--

Soon Sam Santos

Flutter and Delphi Developer at Green. Teacher at SoonClass