How to separate your Routes to unclutter the main entry point file of your project.
For this, we will need two files named "index.js" "homeRoute.route.js".
Index.js will be our app entry point and homeRoute.route.js is where we will be keeping our /Home
Route endpoints.
also for this we will be using the newly introduced import syntax from ES6:
lets start by importing the required packages in our homeRoute.route.js file(which we will be working with first).
import express from express;
const homeRouter = express.Router();
homeRouter.get(`/`,(req,res)=>res.send("this is our frontpage of /home route"))
homeRouter.get(`/about`,(req,res)=>res.send('about page through /home route'))
in here we have created two routes which we will make assessable through /home and /home/about
next we need to export our router for it to be importable in our other file.
export {homeRouter};
write this line below our defined routes inside homeRoute.route.js file.
next we will open our index.js file and import the router we just created.
import express from express;
import {homeRouter} from "./routes/homeRoute.route.js"
remember that we are using the new import syntax here so be sure to check you have the "type" : "module" set in package.json file.
next we need to config our app so that it can use the router and to do that we need to use app.use() functionality provided by express to mount the router in our application.
app.use(`/home`,homeRouter) // this will take two parameters inside it, first one would be the name of our route where we will navigate to and the second our would be that imported router file.
be sure that your are importing {homeRouter} exactly like this because we are exporting a specific codeblock from our route file and importing it without curly braces would result in a error because it would think that you are exporting a default component.
now we need to start up our server and navigate to localhost:3000/home and localhost:3000/home/about to see our result.
Subscribe to my newsletter
Read articles from Aakash directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by