DEV Community

Cover image for Day 16 – Routing (Basic) - Learning Node JS In 30 Days [Mini series]
Muhammad Ali (Nerdjfpb)
Muhammad Ali (Nerdjfpb)

Posted on • Originally published at blog.nerdjfpb.com

Day 16 – Routing (Basic) - Learning Node JS In 30 Days [Mini series]

We’ve already created basic server before so we already know how to start a server and get response. But how we can go on a specific route ?

Alt Text

Solution is not that hard actually. We can check req.url first, which URL client is asking for, then we can provide the data basis on that.

To make the routing, first we can check the request URL using if and send some response based on that.

Alt Text

Run it using node app.js and check in browser http://localhost:3000/home

Alt Text

Now we can easily add new page. ex- about us page

Alt Text

Stop the server and re-run again using node app.js

Alt Text

We can add more pages like this. But what if someone request a URL we didn’t listed ?

Solution is pretty simple just add a if else for that and send tell them not found.

Alt Text

Finally you can check using the wrong URL.

Alt Text

So can you write routes now ?

You can see the graphical version here

Originally it published on nerdjfpbblog. You can connect with me in twitter or linkedin !

You can read the old posts from this series (below)

Top comments (0)