Get And Post Request

Get And Post Request

Get And Post Request, in this Article i will show you how to create a a Get and Post Request

What is a Get Request ?

A get Request is to get the Data from the Server.

What is a Post Request ?

A Post Request is the User Posting Data to the Server

The code in this Article  is the Code extension of this article, here

Read its predecessor before you continue below.

The Code 

 

var express =require('express');
var app =express();

var bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

var ingredients=[
    
    {
        
        "id":"12345",
        "text" : "user"
        
    },
    
    
    {
        
        "id":"45678",
        "text" : "user2"
        
    },
    
    
    
    {
        
        "id":"8888",
        "text" : "user3"
        
    }
    
    
    
    
];

app.get('/',function(request,response){
    
    response.send(ingredients);
});


app.post('/',function(request,response){
    
    var ingredient = request.body;
    if(!ingredient || ingredient.text === ""){
        
        response.status(500).send({error:"Your Ingredient must have a String"});
        
        
    }else{
        
        ingredients.push(ingredient);
        response.status(200).send(ingredients);
        
    }
    
    
    
    
});




app.listen(3000,function(){
    
    console.log("My First API Running on port 3000");
});


The Explanation

  • In this Code i have added an Array of Ingredients var ingredients
  • This “app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); “ is to format the JSON Format
  • Before doing that you need to install the Parser Package through your Batch
  • Now go to the Browser and type http://localhost:3000/ , the browser will display the list of items
  • Now lets create a Post Function using “app.post(‘/’,function(request,response)”
  • When the User input the “argument ” which is request , ( request = User Post) into the function function (request,response)” var ingredient = request.body;” it will assign the User Post into the variable ingredient.
  • The If else Input is to check whether the User input a valid input , if it is an Error , return an error Code, if it is valid !,insert the newly post value by the client “ingredient ” into the list of array ” ingredients”
  • Use Post Man Software to Post the New Value, and then check the results in your Browser

Leave a Comment

eighteen + 2 =