Node.JS Express – GET and POST Methods

In Node.JS you can handle client’s data using GET and POST methods. However, in order to do that, you first have to install the express module. This is also called as building Node.js REST API with Express.

Before starting, let’s get this clear very quickly that what exactly is REST API?

What is REST API?

REST stands for “Representational State Transfer” which relies on stateless client server architecture. The communications between the resources in “RESTful” API follow HTTP standards.

Each resource (like JSON or XML) is represented by URI and the protocols to access these resources are HTTP. Which means that any requests like Create, Read, Update and Delete (CRUD) made against these resources are through HTTP methods.

I hope I’m making some sense over here. Since this is not an article on APIs, I will put the discussion to “REST” and will come right on the topic which is how Node.JS server handles user data using GET or POST methods.

 

GET and POST Methods – Transfer Form Data to Server

The two most widely used methods to transfer user input data to the server are GET and POST methods.

GET method is used when relatively non-confidential information is passed. Once this information is submitted, you can see it in your browser’s URL. Additionally, the information can be cached as well. It is because of this reason the GET is not the best method to transfer confidential information.

On the other hand, POST method is used to transfer information which is relatively confidential and you do not want the browser to cache. One way to differentiate GET and POST methods is that you look in the URL.

If the information that you submitted is part of the URL, then it’s a GET method. If not, then it’s POST method.

See images below to get an idea of what I’m talking about.

 

Handling Form Data Using GET and POST Methods

In the last article we learned how to install and create a Node.js server on windows machine. I hope that by now the NodeJS server is up and running on your systems. So it’s best to jump directly to the point where one can send and receive form data from the client to the server.

In this article, we will collect client’s data from one page using HTML forms and then display that data on other page using first the GET and  then the POST methods in Node.js.

Along the way, I will try to be as explanatory as possible just to make sure that you grasp the full concept.

Note that I’m assuming you have the basic knowledge of  HTML forms before going through this tutorial. If not then I’d highly recommend to learn about HTML forms first.

Create an HTML Form to Collect User Info

First things first, let’s create an HTML form where we will receive basic user info such as first name, last name and gender information.

The information submits as soon as the user clicks the “Submit” button.

Node.js will handle this information and transfer it to another page. This information is then displayed using the JSON “Key Value” format.

Let’s name the HTML page as user_info.html. The HTML code will look something like this


Few points worth considering are:

  1. The URL http://localhost:8888/user in the <form action> tag means that the data will transfer to the page, localhost:8888
  2. localhost is our server created on the local machine while 8888 means that the server will use port 8888 to send and receive the request.
  3. user tells the server to create a page on the fly with the name of user so that the full URL will be http://localhost:8888/user.
  4. Any parameter i.e. the information entered by the user will be displayed after the "user" page in the URL such that if the user enters information as “abc” and the “GET” method is used, as soon as the information is submitted the URL will become http://localhost:8888/user?key=abc

Enough with the details. Let’s create our node.js page which will collect all this information and then parse it in JSON format.

Let’s name the file as server.js

Here’s the code:

Though I have explained every piece of code in the snippet above but still let’s dissect the code line by line.

  1. Let’s start from the bottom (line 34). We’re creating a server which will listen to the requests made by the client through port 8888.
  2. On line 37, if the server connects, we are printing the message if the server is listening to the requests.
  3. Now, let’s jump to the top.
  4. On line 2 we are importing the Express module.
  5. Line 5 is storing the express object in the variable, “app”.
  6. On lines 8 and 9, we are routing the name of the file, "index.html" through the given path. app.get() function takes the name of the file, “index.html” and pass it through a callback function. The res.sendFile() function sends a file on a specific path. __dirname generates the root directory where the server resides. If these lines are not added, the server will not be able to access /index.html (http://localhost:8888/index.html) and you will receive an error, “Cannot GET /index.html”.
  7. Before proceeding further, I’d suggest you to go through the documentation of app.get() and res.sendFile() methods.
  8. From lines 14 to 19 we are again using the app.get() method to route the information submitted by the user (first name, last name and gender) from the index.html page to the “/user” page.
  9. Line 24 is optional. It is just printing the user information on the command prompt as well as soon as the user submits it. It is just to keep track of what is being submitted. Or if anything is even being transferred from the server.
  10. Line number 27 is converting the user information in JSON format.

 

Handling GET Requests in Express

In order to see the Node.js Express REST API GET method in action, do the following:

  1. Open up the node.js command prompt from your start menu.
  2. Type node and then the path where your node.js server is, followed by the server file name. In our case, it will be: c:\wamp\www\node\server.js
  3. Hit “Enter” and a message stating which port the server is listening to will display in the command line. This means that the server is up and running.
  4. Go to your internet browser and type http://localhost:8888/index.html and hit enter to open up the index.html file in the browser.
  5. Enter information in the fields and then click “Submit”.
  6. As soon as you will click submit, the server will route the request to the /user page and you will now see your entered information in the JSON format.
  7. Look at the address bar. User’s entered information is visible in the address bar as well. The reason is the “GET” method which displays your submitted information in the address bar.
  8. Additionally, you can also go and check your command prompt. The information that you submitted is also visible over there as well.Node JS Express Command Prompt

 

Handling POST Requests in Express

In order to handle POST requests in Express JS, there are certain changes that we will need to make. These are:

  1. We will need to download and install body-parser. This is a middle-ware layer which will help us handle POST requests in Node.js using Express framework. Initially, the body-parser used to be a part of express framework but now you have to include and configure separately in your Node.js code.
  2. To download and install body-parser, go to node.js command line and type following code npm install body-parser.
  3. Once installed, our new codes will now be.

And server.js file will now become:

Changes in Server.js file

Make the following changes in the server.js file.

  1. Addition of a code at line 5, var bodyParser = require('body-parser');
  2. Configuration of body-parser for express on lines 11 and 12
    app.use(bodyParser.urlencoded({extended:false}));
    app.use(bodyParser.json());

    app.use() function directs the middle-ware (in our case the body-parser) to the path specified. Read app.use() documentation before proceeding further.
  3. Replace app.get() on line 18 with app.post().
  4. On lines 20, 21 and 22, replace the query method with the body method. So instead of:
    first_name :req.query.first_name
    the code will become:
    first_name: req.body.first_name
    Do the same for last_name and gender as well.
  5. Go ahead, run the server. Now you will be able to handle POST request using Express framework in Node.js.Node JS Express Post Method
  6. Furthermore, to confirm further, you can see the address bar to see if the information entered by the user is being displayed on the address bar. If not, then this means that your POST handler is working just fine.Node JS Express Command Prompt

 

Final Word!

Do let me know if this tutorial helps. Notice any error or got stuck somewhere?

Just leave a message in the comments section. I’d love to help you out.

Please follow and like us:

One thought on “Node.JS Express – GET and POST Methods

Leave a Reply

Your email address will not be published. Required fields are marked *

Sign up to our newsletter!