Table of contents
Working with Express JS
Creating and using Routes Module
This is basically restructuring our code base to look clean and easy to read.
Lets create a new folder and call it routes
. Lets create a new file inside the folder and call it moviesRoute.js
because this route will contain all the routes related to the movies endpoint. Lets move all of the movies routes and all of our route handler functions into the moviesRoute.js
file. Lets import the express()
package. It is a convention to rename the moviesRouter
to router
and then lets export the router
so we can use it in the app.js
file 👇🏼
Lets import the router
in the app.js
file👇🏼
The server still works perfectly👇🏼
Lets create a controllers
folder to keep all of our route handler files. Lets create a moviesController
file inside the folder. Lets move all of our route handlers into the moviesController
file. We want to export multiple functions, we cannot use module.exports
method, we use the exports
object to export each function. So we replace all the const
to exports.
.
To use the route handler functions, we need to import them in the moviesRoutes.js
file using the require()
function. We access the routes from the moviesController
object👇🏼
Lets check the server to see the response. Code still works perfectly👇🏼
Lets create a new file server.js
and move our server code, this is a good practice for excellent file structuring. The server.js
is our starting file, where we start the server and listen to the server request👇🏼
Now lets run: nodemon server.js
to see our response on the server. Our code still works perfectly👇🏼
The server.js
will be our new entry point. Finally lets create a new script in the package.json file to automatically start our entry point file.👇🏼
run: npm start
to automatically start the entry point file
That's all for this lesson.
Next: Understanding Param Middleware
See you soon😊🫡✌🏼...