GET and POST are two of the main Restful Services. In addition to GET and POST, some of the other main services are PUT and DELETE. In this post, I'll be focussing only on GET and POST.
GET is used to fetch already existing resources whereas POST is used to insert a new resource. If I put it according to the example I'm going to use in coding, GET will fetch already existing employee details whereas POST will be used to insert a new employee record/document.
To test the following code, we can use Postman which is a Chrome Desktop Application-that helps in building APIs-to simulate the GET and POST services.
- Create a JavaScript file named employee.model.
The strict notation will be applied when we start the code by giving the following line of code. The strict notation ensures that the programmer does not use any incorrect syntax or any syntax that may change along with time as JavaScript continues to evolve.
'use strict';
Using the require command, we will import the mongoose module required to connect with the
MongoDB.
const mongoose=require('mongoose');
Since we are planning to handle the employee GET and POST requests, we have to maintain
employee information in the database. The following set of code lines are used to create the
structure or schema of the information we are going to store in the database.
const EmployeeSchema=new mongoose.Schema({
name:String,
email:String,
tel:String
});
Then, we are creating a model using our schema.
const Employee=mongoose.model('Employee', EmployeeSchema);
Using module.exports, we are giving the things that are to be exported whenever we require
or import this file from another file.
module.exports=Employee;
- Create another JavaScript file named employees.
'use strict';Using the require command, jmport all the necessary modules. const express=require('express'); const bodyParser=require('body-parser'); const mongoose=require('mongoose');The next particular line of code sets the promise type to be used by mongoose. In this case,by saying global.Promise, we are indicating it to use the native promises.mongoose.Promise=global.Promise;mongoose.connect() is used to connect to MongoDB, and if an error occurs at a given pointfor this line of code, instead of using localhost, you can try using 127.0.0.1 which will work justfine. mongoose.connect('mongodb://localhost:27017/employees', err=>{ if(err) //handles any errors that occur when connecting to the database { console.log(err); process.exit(1); } });Using the line below, we will import the employee.model file we created before with theemployee schema on it. const EmployeeModel=require('./employee.model');The line below is used to create an application out of express.const app=express();express.static() is used to give the location where the server can find the static files like html,css, and js to serve to the client directly. app.use(express.static(__dirname));bodyParser.json() is used to accept JSON objects in the request body. app.use(bodyParser.json());The following command handles the GET restful service of the type or path or route /employees,using which the client will request details of all the employees. The find() command will beused to search for all the documents with the employee details from the MongoDB. exec()command must be used along with find() to execute the query.then() handles what needs to be done with the query results. In this case, res.json() sends theresult in the response made for the request. catch() is used to handle errors that can occur. app.get('/employees', (req, res)=>{ EmployeeModel.find().exec().then(employees=>{ res.json(employees); }).catch(err=>{ console.error(err); res.sendStatus(500); }); });The following command handles the POST restful service of the type or path or route/employees. By accessing the request body through req.body, we will save the parameterspassed by the client which contains the information of the new employee to be added to thedatabase, and then using the save() method, we will save the details to the database. Notethat the client does not need to provide the _id in the request body since MongoDB will beadding it by itself.As in the GET service handling, then() will deal with the result from carrying out the operation,while catch will do the error handling. In this case, the output that the client will get at the endthe operation is the newly added details of the employee. app.post('/employees', (req, res)=>{ const employee=new EmployeeModel(req.body); employee.save().then(employee=>{ res.json(employee); }).catch(err=>{ console.error(err); res.sendStatus(500); }); });Using app.listen(), we are making a server which will listen to the requests from port 3000. Theerror status 500 which we send represents an internal error which simply depicts that theserver is not able to fulfil the request due to an unexpected condition that it came across. app.listen(3000, err=>{ if(err){ //does the error handling console.error(err); return; } console.log('app listening on port 3000'); });
No comments:
Post a Comment