GET & POST Requests in Node.js Using Express-4

February 25, 2015
by Inaam Hussain

In this tutorial we will learn how to handle GET & POST request in node.js using Express 4. Using Express 4 we can easily handle requests. And we have also used Mysql to Fetch and post data from database.

SQL file can be found along with the downloaded code.

DOWNLOAD

Let’s start with installing dependencies and then the code,

Install dependencies

Will going to use following node modules for handling session.

  1. Express 4
  2. Body parser
  3. Mysql

I have created a package.json file that will install all required dependencies. have a look,

package.json
{
"name": "GET-POST-Request",
"version": "0.0.1",
"main": "server.js",
"dependencies": {
        "express": "^4.8.7",
        "mysql":"^2.5.5",
        "body-parser":"^1.12.0"
    }
}

 

How to install dependencies?

By typing following command you can install dependencies,

npm install

Note:You must also have MySQL installed if you are working locally.
 

Initialization & Require

First will include require node modules and http server.
Also we have done connection of Mysql for GET & POST data.

server.js
var app   = require('express')(); // Express App include
var http = require('http').Server(app); // http server
var mysql = require('mysql'); // Mysql include
var bodyParser = require("body-parser"); // Body parser for fetch posted data
var connection = mysql.createConnection({ // Mysql Connection
        host     : 'localhost',
        user     : 'root',
        password : '',
        database : 'abc',
    });
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // Body parser use JSON data

 

GET Request

In GET request we are basically fetching data/values from database and showing as JSON format.See below code,

server.js
app.get('/fetchdata',function(req,res){
    var data = {
        "Data":""
    };
   
    connection.query("SELECT * from testing",function(err, rows, fields){
        if(rows.length != 0){
            data["Data"] = rows;
            res.json(data);
        }else{
            data["Data"] = 'No data Found..';
            res.json(data);
        }
    });
});

Using “app.get(“/url”,function)” we can do URL routing and based on that will fetch data as required.

And “connection.query(“Query”,function)” will used for writing query and in callback will get required data as you can see above code.

 

POST Request

In POST request we are posting data/values and based on that we will validate and send response as JSON.
I’ve created a login API for demo purpose. See below code,

server.js
app.post('/login',function(req,res){
    var email = req.body.email;
    var pass = req.body.password;
    var data = {
        "Data":""
    };
    connection.query("SELECT * from login WHERE email=? and password=? LIMIT 1",[email,pass],function(err, rows, fields){
        if(rows.length != 0){
            data["Data"] = "Successfully logged in..";
            res.json(data);
        }else{
            data["Data"] = "Email or password is incorrect.";
            res.json(data);
        }
    });
});

Using “app.post(“/url”,function)” we can do URL routing and based on that will fetch or post data as required.

And First will get posted data by using “req.body” (i.e : req.body.email & req.body.password ).

Now use that data in query to check whether user is exist or not and based on that it will return response.

 

How to run?

First check whether you have installed Node.js or not.

Then install all required dependencies (i.e : express, express-session & body-parser ) by typing following command in terminal,

npm install

Now, run the server using following command.

node server.js

And now go to browser and hit “localhost:8080″.

 

Watch Video tutorial


 

About

Engineer. Blogger. I like to be updated on new upcoming emerging technologies.

Get notified on our new articles

Subscribe to get the latest on Node.js, Angular, Blockchain and more. We never spam!
First Name:
Email:

9 comments

    • |

      Yes you are right Ido Samuelson.
      My motto here was to explain GET & POST request.
      However I’ve updated the code and made it secure.
      Thanks for the Comment.

    • |

      Yes you are right Vitaly Baum.
      My motto here was to explain GET & POST request.
      However I’ve updated the code and made it secure.
      Thanks for the Comment.

  1. Abdelmajid
    |

    Hi, thanks for this tutorial,

    get is working but post is always returning :

    {
    “Data”: “Email or password is incorrect.”
    }

    • |

      Hi Abdelmajid,
      I think your query is returning no data from database. So first check that your emailid and password is correct.
      If it is correct then it should return successfully logged in.
      Put some conole in that for debugging purpose so that u will come to know what exactly happening. However i have checked and it’s working fine.

      Thanks.

      • Abdelmajid
        |

        in postman, it works when I select x-www-form-urlencoded , but it does not work for the other two tabs :
        form-data
        raw

        • |

          It should work for post request, you need to pass json data in raw tab.
          And other based on that.

  2. |

    I must say it was hard to find your page in google.
    You write awesome articles but you should rank your page
    higher in search engines. If you don’t know how to do it search
    on youtube: how to rank a website Marcel’s way

Leave a Comment