This write-up will demonstrate how to create the routes on the server-side in Node.js. Moreover, the procedure for creating API endpoints based on the CRUD operations will be also provided. So, let’s start!
How to create routes on server-side in Node.js
We have already created a simple Employee Management System application with the React.js front end, Node.js server and built a connection between the server and the MongoDB database. After doing so, we added two models: “employee.model” and “designation.model” with their related schema. We will now create some routes for presenting the models’ information from the MongoDB database using the “Mongoose” library.
The next step is to add the API routes to utilize them for performing the CRUD operations. We will create a “designation” and an “employee” route for demonstration. To do so, firstly, we will create a new “route” folder on the server-side:
We will name the newly created folder as “routes”:
Next, click on the “routes” folder and select the “New File” option for creating an “employee.js” route file:
By utilizing the same method, we will create another route file, “designation.js” in the routes folder:
As you can see, we have created two routes file, “employee.js” and “designation.file” in the “routes” folder:
In the terminal, execute the following command for setting up the React router as it is the standard library that can be used for routing:
After doing so, add the following line in your Project’s “App.js” file:
In the next step, open up the “employee.js” file ad add the below-given code in it:
In this code, we have added two endpoints. The first endpoint will handle the incoming HTTP “GET” requests on the “/employees/” URL path. Next, the “Employee.find()” method is called for getting the list of Employees from the MongoDB database. This find() method will return a promise, and the result will be returned in JSON format.
The second endpoint which we have added in our “employee” route file, will handle the incoming HTTP “POST” requests on the “/employees/add/ URL path. The new employee name will be considered as part of the request. After receiving the new employee name, a new instance of the Employee will be created, and then the “save()” function will save the new Employee record in the MongoDB database. If the specified operation is completed successfully, then the “Employee added!” string will be returned:
let Employee = require('../models/employee.model');
router.route('/').get((req, res) => {
Employee.find()
.then(employees => res.json(employees))
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/add').post((req, res) => {
const employeename = req.body.employeename;
const newEmployee = new Employee({employeename});
newEmployee.save()
.then(() => res.json('Employee added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
module.exports = router;
Next, open up the “designation.js” file for creating the designations routes:
Now, firstly, we will add the same endpoints which we have added in the “employees.js” routes file. However, this time we will break all three fields “employeename”, “designation”, and “date” from the submitted data:
let Designation = require('../models/designation.model');
router.route('/').get((req, res) => {
Designation.find()
.then(designations => res.json(designations))
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/add').post((req, res) => {
const employeename = req.body.employeename
const designation = req.body.designation;
const date = Date.parse(req.body.date);
const newDesignation = new Designation({
employeename,
designation,
date,
});
newDesignation.save()
.then(() => res.json('Designation added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
module.exports = router;
The previously added endpoints can be utilized for reading and creating the designation items. Now, we will create two routes for the remaining CRUD operations, which are “update” and “delete”.
In the below-given code “/:id” GET endpoint will return a designation item that will have the specified item, and it will be deleted using the “delete()” function. The “/update/:id” POST endpoint will update the existing designation items. For the update endpoint, firstly, we will retrieve the existing designation item from the MongoDB database based on the specified id. After doing so, we will set the designation property values, such as “employeename”, “designation”, and “date” to the values received in the request body. Lastly, we will call the “designation.save()” method for saving the updated designation object in our database:
Designation.findById(req.params.id)
.then(designation => res.json(designation))
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/:id').delete((req, res) => {
Designation.findByIdAndDelete(req.params.id)
.then(() => res.json('Designation deleted.'))
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/update/:id').post((req, res) => {
Designation.findById(req.params.id)
.then(designation => {
designation.employeename = req.body.employeename;
designation.designation = req.body.designation;
designation.date = Date.parse(req.body.date);
designation.save()
.then(() => res.json('Designation updated!'))
.catch(err => res.status(400).json('Error: ' + err));
})
.catch(err => res.status(400).json('Error: ' + err));
});
Now, let us tell the Node.js server to use the routes we created in the “routes” folder. To do so, we will open the “server.js” JavaScript file of our server-side:
This is how our “server.js” file looks like at this point:
The code you are going to add should be placed before the “app.listen(port, function() ” line:
Now, add the following code in the highlighted section:
const employeesRouter = require('./routes/employees');
app.use('/designations', designationsRouter);
app.use('/employees', employeesRouter);
The first two lines in the above-given code will load the router from the “designations” and “employees” files which we have created in the “routes folder,” and then the routers are defined as middleware:
Press “CTRL+S” to save the added changes into your Node.js server-side file:
After creating the routes on the server-side in Node.js, you can test them using any API testing application such as Postman and Insomnia.
Conclusion
The process in which the client requests are processed by the server-side of the Node.js is defined as routing. In routing, a route is a section of “express” code that links the HTTP requests such as POST, GET, DELETE, and PUT to a URL pattern or path and then adds a function for handling the pattern. This write-up demonstrated how to create the routes on the server-side in Node.js. Moreover, the procedure for creating API endpoints based on the CRUD operations is also provided.