Handling GET and POST HTTP Request in NodeJS and Express Application



From Last few months i worked a lot on Full Stack JavaScript Development, and from my experience i found some best and simple ways to handle different HTTP Request in Node & Express API, In this article we are going to make a simple CRUD(Create Read Update and Delete ) API.

If you are not aware of setting up a Node and Express Application Kindly refer my previous article here.


So Lets get Started:

Like a normal Express Application in line number 1 & 2 we are importing express and initialising it in "app" constant, now "app" is referencing our whole applications.

1
2
const express = require('express'); //importing  Express 
const app = express(); //initialising Express app 
To Keep this Example simple we are going to use an array to save our data instead of a Database.

While Developing an API, Validation is an important part that needs to be considered.
for validation we are going to use "joi" a node module from npm using the command "npm install joi"  and then after successful instillation import joi in similar fashion as we import other node modules. .


1
2
3
const express = require('express'); 
const app = express(); 
const Joi = require('joi'); //importing Joi for Validation

In this API we are simply going to do operations on a simple array as our database which contains a list of locations with a unique key.

1
2
3
4
5
6
7
8
const express = require('express');
const app = express();
const Joi = require('joi');
const locations = [
  { id: 1, name: 'Jalandhar' },  
  { id: 2, name: 'New Delhi' },  
  { id: 3, name: 'Chandigarh' },  
]; // initialising an array of object containing unique key with every location.

We are now ready to define our first route and handle the first request i.e "GET"

In our first route that is "/locations" will return the array of all the locations with keys.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
const express = require('express');
const app = express();
const Joi = require('joi');
const locations = [
  { id: 1, name: 'Jalandhar' },  
  { id: 2, name: 'New Delhi' },  
  { id: 3, name: 'Chandigarh' },  
];

app.get('/locations', (req, res) => {
  res.send(locations);
});//Defining the first route that returns all the array of all the locations

Now we are going to define a "POST" route , which accepts only location value and insert it into the locations array and we are going to implement little bit of validation using joi .



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const express = require('express');
const app = express();
const Joi = require('joi');
const locations = [
  { id: 1, name: 'Jalandhar' },  
  { id: 2, name: 'New Delhi' },  
  { id: 3, name: 'Chandigarh' },  
];

app.get('/locations', (req, res) => {
  res.send(locations);
});

app.post('/location', (req, res) => {    /*Defining the route for POST Request */
  const { error } = validateLocation(req.body);  /*checking for errors in validation*/
  if (error) return res.status(400).send(error.details[0].message); /*if their is error send back the error */
  /*if validation is successful then we go further */
  const location = { /* Creating a location object*/
    id: locations.length + 1,  /*Auto Incrementing the key*/
    name: req.body.name  /* Assigning location name to the name*/
  };
  locations.push(location); /*Pushing the new location object to locations array*/

  res.send(location); /*Returning the newly created location and its key*/
});



Now its time to define the "validateLocation" Function



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const express = require('express');
const app = express();
const Joi = require('joi');
const locations = [
  { id: 1, name: 'Jalandhar' },  
  { id: 2, name: 'New Delhi' },  
  { id: 3, name: 'Chandigarh' },  
];

app.get('/locations', (req, res) => {
  res.send(locations);
});

app.post('/location', (req, res) => {    /*Defining the route for POST Request */
  const { error } = validateLocation(req.body);  /*checking for errors in validation*/
  if (error) return res.status(400).send(error.details[0].message); /*if their is error send back the error */
  /*if validation is successful then we go further */
  const location = { /* Creating a location object*/
    id: locations.length + 1,  /*Auto Incrementing the key*/
    name: req.body.name  /* Assigning location name to the name*/
  };
  locations.push(location); /*Pushing the new location object to locations array*/

  res.send(location); /*Returning the newly created location and its key*/
});

function validateLocation(location) {
  const schema = {
    name: Joi.string().min(3).required()
  }; /*Defining the schema and validation rules (minimum character should be 3 and this fiels is required) */

  return Joi.validate(location, schema);
}

You Can test these API using tools like POSTMAN.

In Next article we are going to Handle PUT and DELETE Request.

Feel Free to ask any query if u have ! Keep Noding

Comments

Popular posts from this blog

Evolution of Internet of Things(IoT)

Developing a Progressive Web App from a Static Web App.

Building a Progressive Web Apps- CodeLab