More
    Web DevelopmentBackend DevelopmentHandling GET and POST Requests in Express

    Handling GET and POST Requests in Express

    GET and POST Requests are the two most widely used HTTP methods in Express. Let us see their working in detail with an example project.

    Before moving to the explanation, we will create an empty Node project and initialize npm and install some required node modules.

    Creating the Project:

    Fire up the terminal and move to the directory where you want your project folder and enter the following commands:

    $ cd Desktop/

    This will change the working directory to the Desktop, you can paste the path of the folder where you want your project folder.

    $ mkdir SimpleCalculator

    This command will make a folder named ‘SimpleCalculator’ on the desktop. Now, again change your working directory to ‘SimpleCalculator’.

    $ cd SimpleCalculator/

    Create two files named index.html and calculator.js using the following commands

    $ touch index.html calculator.js

    Initialize the npm using the following command

    $ npm init

    It would ask you to set some options, which you can leave as they are and press the enter key till the process is done.

    Now, we will be installing some important npm modules

    $ npm install express body-parser

    Open up your code editor or Visual Studio Code (Preferred) and import the newly installed node modules using the following syntax in calculator.js

    const express = require("express"); //This line will import express module
    const bodyParser = require("body-parser"); //This line will import body-parser module
    const app = express(); // This line will ask the app to use express module.
    app.use(bodyParser.urlencoded({extended: true})); /* This line will ask the app to use body-parser module */

    Open up the index.html file and create a form to ask for two numbers and a button to send the post request.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Calculator</title>
    </head>
    <body>
    
        <form action="/" method="post">
    
            <input type="text" name="num1" placeholder="First Number">
            <input type="text" name="num2" placeholder="Second Number">
            <button type="submit" name="submit">Calculate</button>
    
        </form>
        
    </body>
    </html>

    Notice the ‘action’ and ‘method’ attribute in the form tag. The action attribute defines the path where the method will execute, as in our case, “/” means that the form data will be executed to the root directory of the project server.

    The ‘method’ attribute defines the type of method we need to execute the input fields data. Like in our case, we are using the “post” method, which will send the post request to the server.

    The two input fields have their name attribute as “num1” and “num2”, which we will use later to parse the data using body-parser.

    Add the listen method into your calculator.js file for the app to listen for the client requests on port 3000.

    app.listen(3000, function () { 
        console.log("Server is started on port 3000");
     });

    GET Method:

    GET method is invoked whenever a client tries to send the get request for a particular directory, and ask for the response from the server.

    Add the following code to your calculator.js file.

    app.get("/", function(req, res){
        res.sendFile(__dirname + "/index.html");
    });

    This syntax will handle the request when the client browser will try to access the “/”, i.e., root directory of the server.

    A callback function is passed in this method to send a response to the client.

    We are sending the response (res) through the sendFile method as a html file, which, in our case is named as index.html and is located in the root directory of our project.

    POST Method:

    POST method is invoked when the client browser sends a request to post some data to the server.

    Add the following code to your calculator.js file.

    app.post("/", function (req, res) { 
        
        var num1 = Number(req.body.num1);
        var num2 = Number(req.body.num2);
    
        var result = num1 + num2;
    
        res.send("The sum of the two values is: " + result);
    
     });

    This syntax will listen for the post requests being made to the server. When a user enters the value in the two fields num1 and num2, and press the “Calculate” button, the client will try to post the data to the server which is listening for post requests at the “/” directory.

    A callback function is passed to the post method which provides us will the functionality to retrieve the data and send back a response to the client side.

    The two variables num1 and num2 are storing the data parsed by the body-parser from the request (req). The req.body.num1 and req.body.num2 must exactly match with the name attribute of the input tags in the HTML form.

    The result is stored in a variable ‘result’ and sent through the response method ‘res’.

    Starting the server:

    Go to your terminal and enter the following command

    $ node calculator.js

    Now, open up your browser and enter the following address into the address bar,

    localhost:3000

    You will get the desired result, while your important logic is running behind the scenes, i.e., in your server.

    Download this complete node project:

    Sponsored

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here

    Subscribe Today

    GET EXCLUSIVE FULL ACCESS TO PREMIUM CONTENT

    Get unlimited access to our EXCLUSIVE Content and our archive of subscriber stories.

    Exclusive content

    Latest article

    More article