How HTTP POST requests work in Node ?
The HTTP POST method is employed by the World Wide Web to send data to a server. This request method is characterized by the inclusion of data in the request body, and the type of this body is specified by the Content-Type header. Express.js, a web application framework for Node, facilitates the creation of servers and handling various HTTP requests, such as GET and POST.
Syntax:
app.post(route, function(req, res){
//this is a callback function
})
Steps to Create the Application:
Step 1: Initialising the Node App using the below command:
npm init -y
Step 2: Installing the required packages:
npm i express body-parser
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"body-parser": "^1.20.2",
"express": "^4.18.2",
}
Example: Below is the basic example of the HTTP POST request using nodejs:
- User accesses the server at
http://localhost:3000/
. - The server sends the HTML form for the user to input two numbers.
- User enters numbers and submits the form.
- The server receives the POST request, extracts the numbers, performs addition, and sends the result as a response.
Javascript
const express = require( "express" ); const bodyParser = require( "body-parser" ) // New app using express module const app = express(); app.use( bodyParser.urlencoded({ extended: true }) ); app.get( "/" , function (req, res) { res.sendFile( __dirname + "/index.html" ); }); app.post( "/" , function (req, res) { var num1 = Number(req.body.num1); var num2 = Number(req.body.num2); var result = num1 + num2; res.send( "Addition - " + result); }); app.listen(3000, function () { console.log( "server is running on port 3000" ); }) |
HTML
<!DOCTYPE html> < html lang = "en" dir = "ltr" > < head > < meta charset = "utf-8" > < title >Calculator</ title > </ head > < body > < h1 >Simple Calculator.</ h1 > < form action = "/" method = "post" > < input type = "text" name = "num1" placeholder = "First Number" > < input type = "text" name = "num2" placeholder = "Second Number" > < button type = "submit" name = "submit" > calculator </ button > </ form > </ body > </ html > |
Output: