Express.js is the most popular framework for Node.js, so I learn Express.js. It’s so convenient to develop a Node server with Express.js
Before that, we have to know some basics about Express.
After we created package management with npm init
use npm i express --save
to install express package.
I use app.js as my root file with scripting in package.json file.
so we could start a server with nodemon by the command in cmd or terminal with npm start
. Nodemon is a package to automatically restart the server for the coder every time the code has changed and saved.
so from now on let’s get into details of routing with Express.js
This is my app.js file
For node.js, I uses require({route path}) to import my route module. which the “userRoutes” is exported as a module.
This is the treeview of my application files
This home.js inside a routes folder
which home.html in views is just Html file we want to send as a response for the browser to display it.
And use Router method provided by express to set up a route module.
Not only app.use() is for all types of http request. It has .get .post .put .delete and so on to access the right function with right method.
Another trick is the nested routes. If we combined both codes
would be
app.use('/user', (req, res, next) => { router.get('/home', someresponse)})
this actually requires the user to go to localhost:8080/user/home
and if user only type in localhost:8080/user it will return status code of 404 which is the page not found, because there isn’t a user module.
It’s pretty simple and easy to work with routes of Express.js just couple of lines of codes.