Demonstration of GET method using NodeJS and ExpressJS to find single record

Rajnilari2015
Posted by Rajnilari2015 under Node.js category on | Points: 40 | Views : 384
In the below code, we will find an example that demonstrates the use of GET method using NodeJS and ExpressJS to find single record

//add the express module
var express = require('express');

//create an instance of express module
var app = express();

//prepare the Employee data source/model
var employees =
[
{
"EmployeeID" :1 ,
"EmployeeName" : "RNA Team",
"Salary" : "200000",
"Address" : "Bangalore"
},
{
"EmployeeID" :2 ,
"EmployeeName" : "Mahesh Samabesh",
"Salary" : "100000",
"Address" : "Hydrabad"
},
{
"EmployeeID" :3 ,
"EmployeeName" : "Rui Figo",
"Salary" : "50000",
"Address" : "Dallas"
},
{
"EmployeeID" :4 ,
"EmployeeName" : "Indradev Jana",
"Salary" : "456789",
"Address" : "Los Angles"
},
{
"EmployeeID" :5 ,
"EmployeeName" : "Suresh Shailesh",
"Salary" : "1234567",
"Address" : "Patna"
}
];

//Get single Employee record
app.get('/:EmployeeID', function (req, res) {

var employeeID = req.params.EmployeeID;

//Get Employee Records whose EmployeeID = get the EmployeeID at runtime
var filteredEmployee = [];

for(var i= 0; i< employees.length; i++){

if(employees[i].EmployeeID == employeeID){
filteredEmployee.push(employees[i]);
}
} //end Loop
employees = filteredEmployee;
res.send(employees);
});

//run the server
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;

console.log('Server started and is listening at :> http://%s:%s', host, port);
});


In the beginning, we have imported the needed modules and prepared the model data.Since express routes are based on HTTP verbs, so the app.get() method fetches the records from the URI specified.And finally the app starts a server and listens on port 3000 for connection. It will respond with the Employee Records for requests to the root URL (/) or route.We have passed the EmployeeID at runtime and filter the records.Internally, Express converts a route to regular expression.

Comments or Responses

Login to post response