Basic Routing in ExpressJS
Hello There,
Lets talk about Routes. A Route is simply an entry point into your Application. Routes are very common, example of a route is http://apple.com/mac.
In my Previous Article we got to know how to set up our ExpressJS Application with a Structure which is good, but if you’re used to PHP Frameworks, for example Laravel, you would know that web routes are handled in a single file.
But in ExpressJS its a bit Different, so let’s flash Back to the Structure we currently have
Our Attention would be on the routes
directory and the app.js
file.
Right now our application has two routes http://localhost:3000 and http://localhost:3000/users. So without much complication let’s create a route for food
we are going to make a route for http://localhost:3000/food.
Lets Get Started
- Create a
food.js
file in theroutes
directory
Then, add these lines of code to food.js
- Open
app.js
in you root directory
Now Observe line 8 & 9
and 25 & 26
We are going to replicate these but in the food
way in a new line like this……
When you’re sure you have these in your app.js
file fire up Terminal, change directory to your express-practice
folder and run npm start
then visit http://localhost:3000
And you should be able to see the requests made in Terminal like this…
If you want to achieve something like http://localhost:3000/food/beans do the following:
- Open
food.js
in theroutes
directory
Modify your code like this
Now try loading http://localhost:3000/food/beans on your web browser, you would get an “Error 404: Not found”.
No need to panic, just restart your node server by pressing ctrl + c
and running npm start
again, when you do that you should have a flawless application.
At this point you should have understood the basics of routing in ExpressJS, you can read up more on routing from the official documentation
Note
These articles are not intended to teach you everything about ExpressJS but to give you a basic understanding of how to work with it, so you are required to have basic understanding of programming.
Thank you for reading to this point, I would be working on the next chapter.
Bye.