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:
- The URL
tag means that the data will transfer to the page, localhost:8888
- 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.
usertells the server to create a page on the fly with the name of user so that the full URL will be
- 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.
- 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.
- On line 37, if the server connects, we are printing the message if the server is listening to the requests.
- Now, let’s jump to the top.
- On line 2 we are importing the Express module.
- Line 5 is storing the express object in the variable, “app”.
- 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.
__dirnamegenerates 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”.
- Before proceeding further, I’d suggest you to go through the documentation of app.get() and res.sendFile() methods.
- 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.
- 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.
- 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:
- Open up the node.js command prompt from your start menu.
nodeand then the path where your node.js server is, followed by the server file name. In our case, it will be:
- 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.
- 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.
- Enter information in the fields and then click “Submit”.
- 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.
- 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.
- Additionally, you can also go and check your command prompt. The information that you submitted is also visible over there as well.
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:
- 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.
- To download and install body-parser, go to node.js command line and type following code
npm install body-parser.
- Once installed, our new codes will now be.
server.js file will now become:
Changes in Server.js file
Make the following changes in the server.js file.
- Addition of a code at line 5,
var bodyParser = require('body-parser');
- Configuration of body-parser for express on lines 11 and 12
app.use()function directs the middle-ware (in our case the body-parser) to the path specified. Read app.use() documentation before proceeding further.
app.get()on line 18 with
- On lines 20, 21 and 22, replace the query method with the body method. So instead of:
the code will become:
Do the same for last_name and gender as well.
- Go ahead, run the server. Now you will be able to handle POST request using Express framework in Node.js.
- 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.
- 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.
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.