Create Separate Routes File in Node Express.js
This tutorial will teach you how to create a separate route file in Node.js. Routing describes how an application’s endpoints (URIs) respond to client requests. You define routing by using Express app object methods that correspond to HTTP methods, such as an app.get()
for GET requests and app.post()
for POST requests, and even PUT and DELETE requests.
To avoid clustering of all routes in our index.js, we create route files in Express.js. It will help us to separate routes by creating separate files for each.
Creating Separate Routes File in Node Express.js
We will be using the express module for the same. To install express, type this on terminal
npm i express
In the index.js file first, include the module using require()
the method and define the app and port for the same.
const express=require('express') const app=express(); const PORT=8080
And we call app.listen()
to make sure the port is running
app.listen(PORT,()=>{ console.log("Server is running") })
Now we create a folder called routes, where we will save all our route file
For example, we have created User.js and contact.js
In User.js
We will include the Express module and also an express.Router() function to create a new router object. And then we specify our endpoint. In this example, we are using the get method likewise you can specify all the methods for route /user.
const express=require('express') const router=express.Router() router.get("/",(req,res)=>{ res.send("User route is displaying data") })
Finally, we export this module
module.exports=router;
Now similarly we do that in our other route file,
Contact.js
const express=require('express') const router=express.Router() router.get("/",(req,res)=>{ res.send("Contact route is displaying data") }) module.exports=router;
Now in our index.js file
Now we define variables that are associated with their respective route
const userRoute=require('./routes/User') const contactRoute=require('./routes/Contact')
And then, we use the app.use() to use the routes.
app.use("/user",userRoute) app.use("/contact",contactRoute)
Here’s the complete code,
Index.js
const express=require('express') const app=express(); const PORT=8080 const userRoute=require('./routes/User') const contactRoute=require('./routes/Contact') app.use("/user",userRoute) app.use("/contact",contactRoute) app.listen(PORT,()=>{ console.log("Server is running") })
User.js
const express=require('express') const router=express.Router() router.get("/",(req,res)=>{ res.send("User route is displaying data") }) module.exports=router;
Contact.js
const express=require('express') const router=express.Router() router.get("/",(req,res)=>{ res.send("Contact route is displaying data") }) module.exports=router;
Output
Good article. Helped me a lot. Can’t wait for more articles on node Js from you.
Never thought routes folder is this important. Thanks a lot!!!