Handling GET and POST Request in NodeJS

Last updated on Jan 18 2023
Prabhas Ramanathan

Table of Contents

Express.js GET Request

GET and POST both are two common HTTP requests used for building REST API’s. GET requests are used to send only limited amount of data because data is sent into header while POST requests are used to send large amount of data because data is sent in the body.
Express.js facilitates you to handle GET and POST requests using the instance of express.

Express.js GET Method Example 1

Fetch data in JSON format:

Get method facilitates you to send only limited amount of data because data is sent in the header. It is not secure because data is visible in URL bar.
Let’s take an example to demonstrate GET method.

File: index.html

1. <html> 
2. <body> 
3. <form action="http://127.0.0.1:8081/process_get" method="GET"> 
4. First Name: <input type="text" name="first_name"> <br> 
5. Last Name: <input type="text" name="last_name"> 
6. <input type="submit" value="Submit"> 
7. </form> 
8. </body> 
9. </html>

 

File: get_example1.js

1. var express = require('express'); 
2. var app = express(); 
3. app.use(express.static('public')); 
4. 
5. app.get('/index.html', function (req, res) { 
6. res.sendFile( __dirname + "/" + "index.html" ); 
7. }) 
8. app.get('/process_get', function (req, res) { 
9. response = { 
10. first_name:req.query.first_name, 
11. last_name:req.query.last_name 
12. }; 
13. console.log(response); 
14. res.end(JSON.stringify(response)); 
15. }) 
16. var server = app.listen(8000, function () { 
17. 
18. var host = server.address().address 
19. var port = server.address().port 
20. console.log("Example app listening at http://%s:%s", host, port) 
21. 
22. })

 

 

Open the page index.html and fill the entries:

n 11

Now, you get the data in JSON format.

n 12

Express.js GET Method Example 2

Fetch data in paragraph format

File: index.html

1. <html> 
2. <body> 
3. <form action="http://127.0.0.1:8000/get_example2" method="GET"> 
4. First Name: <input type="text" name="first_name"/> <br/> 
5. Last Name: <input type="text" name="last_name"/><br/> 
6. <input type="submit" value="Submit"/> 
7. </form> 
8. </body> 
9. </html>

 

File: get_example2.js

1. var express = require('express'); 
2. var app=express(); 
3. app.get('/get_example2', function (req, res) { 
4. res.send('<p>Username: ' + req.query['first_name']+'</p><p>Lastname: '+req.query['last_name']+'</p>'); 
5. }) 
6. var server = app.listen(8000, function () { 
7. var host = server.address().address 
8. var port = server.address().port 
9. console.log("Example app listening at http://%s:%s", host, port) 
10. })

 

Open the page index.html and fill the entries:

n 13

Output:

n 14

Express.js GET Method Example 3

File:index.html

1. <!DOCTYPE html> 
2. <html> 
3. <body> 
4. <form action="http://127.0.0.1:8000/get_example3"> 
5. <table> 
6. <tr><td>Enter First Name:</td><td><input type="text" name="firstname"/><td></tr> 
7. <tr><td>Enter Last Name:</td><td><input type="text" name="lastname"/><td></tr> 
8. <tr><td>Enter Password:</td><td><input type="password" name="password"/></td></tr> 
9. <tr><td>Sex:</td><td> 
10. <input type="radio" name="sex" value="male"> Male 
11. <input type="radio" name="sex" value="female">Female 
12. </td></tr> 
13. <tr><td>About You :</td><td> 
14. <textarea rows="5" cols="40" name="aboutyou" placeholder="Write about yourself"> 
15. </textarea> 
16. </td></tr> 
17. <tr><td colspan="2"><input type="submit" value="register"/></td></tr> 
18. </table> 
19. </form> 
20. </body> 
21. </html>

 

File: get_example3.js

1. var express = require('express'); 
2. var app=express(); 
3. 
4. app.get('/get_example3', function (req, res) { 
5. res.send('<p>Firstname: ' + req.query['firstname']+'</p> 
6. <p>Lastname: '+req.query['lastname']+'</p><p>Password: '+req.query['password']+'</p> 
7. <p>AboutYou: '+req.query['aboutyou']+'</p>'); 
8. }) 
9. 
10. var server = app.listen(8000, function () { 
11. var host = server.address().address 
12. var port = server.address().port 
13. console.log("Example app listening at http://%s:%s", host, port) 
14. })

 

n 15

Express.js POST Request

GET and POST both are two common HTTP requests used for building REST API’s. POST requests are used to send large amount of data.
Express.js facilitates you to handle GET and POST requests using the instance of express.

Express.js POST Method

Post method facilitates you to send large amount of data because data is send in the body. Post method is secure because data is not visible in URL bar but it is not used as popularly as GET method. On the other hand GET method is more efficient and used more than POST.
Let’s take an example to demonstrate POST method.

Example1:

Fetch data in JSON format

File: Index.html

1. <html> 
2. <body> 
3. <form action="http://127.0.0.1:8000/process_post" method="POST"> 
4. First Name: <input type="text" name="first_name"> <br> 
5. Last Name: <input type="text" name="last_name"> 
6. <input type="submit" value="Submit"> 
7. </form> 
8. </body> 
9. </html>

 

File: post_example1.js

1. var express = require('express'); 
2. var app = express(); 
3. var bodyParser = require('body-parser'); 
4. // Create application/x-www-form-urlencoded parser 
5. var urlencodedParser = bodyParser.urlencoded({ extended: false }) 
6. app.use(express.static('public')); 
7. app.get('/index.html', function (req, res) { 
8. res.sendFile( __dirname + "/" + "index.html" ); 
9. }) 
10. app.post('/process_post', urlencodedParser, function (req, res) { 
11. // Prepare output in JSON format 
12. response = { 
13. first_name:req.body.first_name, 
14. last_name:req.body.last_name 
15. }; 
16. console.log(response); 
17. res.end(JSON.stringify(response)); 
18. }) 
19. var server = app.listen(8000, function () { 
20. var host = server.address().address 
21. var port = server.address().port 
22. console.log("Example app listening at http://%s:%s", host, port) 
23. })

 

So, this brings us to the end of blog. This Tecklearn ‘Handling GET and POST Request in NodeJS’ blog helps you with commonly asked questions if you are looking out for a job in NodeJS Programming. If you wish to learn NodeJS and build a career in NodeJS Programming domain, then check out our interactive, Node.js Training, that comes with 24*7 support to guide you throughout your learning period.

Node.js Training

About the Course

Tecklearn’s Node.js certification training course familiarizes you with the fundamental concepts of Node.js and provides hands-on experience in building applications efficiently using JavaScript. It helps you to learn how to develop scalable web applications using Express Framework and deploy them using Nginx. You will learn how to build applications backed by MongoDB and gain in-depth knowledge of REST APIs, implement testing, build applications using microservices architecture and write a real-time chat application using Socket IO. Accelerate your career as a Node.js developer by enrolling into this Node.js training.

Why Should you take Node.js Training?

• As per Indeed.com data, the average salary of Node.js developer is about $115000 USD per annum.
• IBM, LinkedIn, Microsoft, GoDaddy, Groupon, Netflix, PayPal, SAP have adopted Node.js – ITJungle.com
• There are numerous job opportunities for Node.js developers worldwide. The job market and popularity of Node.js is constantly growing over the past few years.

What you will Learn in this Course?

Introduction to Node.js

• What is Node.js?
• Why Node.js?
• Installing NodeJS
• Node in-built packages (buffer, fs, http, os, path, util, url)
• Node.js Modules
• Import your own Package
• Node Package Manager (NPM)
• Local and Global Packages

File System Module and Express.js

• File System Module
• Operations associated with File System Module
• JSON Data
• Http Server and Client
• Sending and receiving events with Event Emitters
• Express Framework
• Run a Web Server using Express Framework
• Routes
• Deploy application using PM2 and Nginx

Work with shrink-wrap to lock the node module versions

• What is shrink-wrap
• Working with npmvet
• Working with outdated command
• Install NPM Shrinkwrap

Learn asynchronous programming

• Asynchronous basics
• Call-back functions
• Working with Promises
• Advance promises
• Using Request module to make api calls
• Asynchronous Commands

Integration with MongoDB and Email Servers

• Introduction to NoSQL Databases and MongoDB
• Installation of MongoDB on Windows
• Installation of Database GUI Viewer
• Inserting Documents
• Querying, Updating and Deleting Documents
• Connect MongoDB and Node.js Application
• Exploring SendGrid
• Sending emails through Node.js application using SendGrid

REST APIs and GraphQL

• REST API
• REST API in Express
• Postman
• MongoDB Driver API
• Express Router
• Mongoose API
• GraphQL
• GraphQL Playground

Building Node.js Applications using ES6

• ES6 variables
• Functions with ES6
• Import and Export withES6
• Async/Await
• Introduction to Babel
• Rest API with ES6
• Browsing HTTP Requests with Fetch
• Processing Query String
• Creating API using ES6
• Building Dashboard API
• Creating dashboard UI with EJS
• ES6 Aside: Default Function Parameters
• Data Validation and Sanitization

User Authentication and Application Security

• Authentication
• Types of Authentication
• Session Vs Tokens
• JSON Web Tokens
• Bcrypt
• Node-local storage

Understand Buffers, Streams, and Events

• Using buffers for binary data
• Flowing vs. non-flowing streams
• Streaming I/O from files and other sources
• Processing streams asynchronously
• File System and Security

Build chat application using Socket.io

• Getting Started
• Adding Socket.io To Your App
• Exploring the Front-end
• Sending Live Data Back & Forth
• Creating the Front-end UI
• Showing Messages In App
• Working with Time
• Timestamps
• Show Message Time In Chat App
• Chat application Project

Microservices Application

• Why Microservices?
• What is Microservices?
• Why Docker?
• What is Docker?
• Terminologies in Docker
• Child Processes
• Types of child process

 

0 responses on "Handling GET and POST Request in NodeJS"

Leave a Message

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