JavascriptNode.JSProgrammingTechnology

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. Moreover, when you open a JSON file in your browser, it’s not formatted in a way that is easy to read. Therefore, when you’re trying to make sense of the data inside, this can be frustrating. If this is the case with you, then looking for ways to learn How To Open JSON File would be needed.

Unlike JSON, there are websites where you can get data in the form of a YAML file. Extracting formatted data from those files might seem difficult. This problem can be solved since you can use the yaml diff checker to know the difference between those two data sets where one is formatted well and another one is unformatted. I hope I’m making some sense over here. Now coming back to the previous discussion about APIs, 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
    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
  7. However, if you have plenty of information in your JSON file and need to convert it into human-readable content, you may use ATOM or Notepad.

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.

13 thoughts on “Node.JS Express – GET and POST Methods

  • Pingback: How to Install NodeJS on Windows 8 (64-bit 32-bit)

  • Pingback: Create Twitter Bot Using Node.js Twit Package - The Usual Stuff

  • Randolph

    I’ve been on a wild goose chase for the better part of 3 days trying to figure this out. Every resource/help out there says something different and completely out of the scope of the issue.

    This post explained everything in the detail and flow I wish I saw 150 searches ago. Thank you! Bookmarked.

  • good job

    Thank you so much for clear instructions! I’ve been unclear of the use of ajax calls separate from get/post methods in node.js

  • i used get method to send data to backend ,but it is used to send undefined instead of original values.what is the reason for this fault.

    • Hi Harish,

      Unfortunately, with this limited information, I won’t be able to guide you.

      You may need to upload your full code.

      Thanks.

  • Wоw, awesome bloց layoᥙt! How l᧐ng have you been blοɡging for?

    you make blogging look eаsy. Tһe overall look of your site is fantastic, let
    alone the content!

  • Hi there,

    I get this message when I try to load http://localhost:8888/index.html

    ReferenceError: _dirname is not defined

    How might I resolve this?

    Thanks in advance.

    • Hi Szewah,

      Did you try using double underscores instead of a single one __dirname instead of _dirname

      This is all that I can figure out from the limited information that you’ve provided.

      Thank you.

  • Hi there
    I need some help
    when i use app.post, the website can’t visible. It just say “can not /get”
    Can anyone help me ? Thank you

  • Rakesh Mali

    You need to update your files name: “user_info.html” to “index.html” and
    your action attribute to “/user” end-point instead of “/process_get”

  • Pingback: Beginners Guide to the Callback Function in Javascript - The Usual Stuff

  • Amazing It helped me a lot

Comments are closed.