How to receive post parameter in Express.js
How you can receive parameter in post method using express can be use by inbuilt middleware name express.urlencoded() and req.body Object.
How to Receive Post Parameter in Express
Post Parameter can be recieved by form using express.urlencoded()
This is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on body-parser.
The express.urlencoded() middleware is used to parse the data that is comming from client side.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Post Parameter in Express </title>
</head>
<body>
<h2>Post in ExpressJS</h2>
<form action="/submit" method="post">
<label for="name">Name</label>
<input type="text" name="name" id="name"><br><br>
<label for="emailid">Email</label>
<input type="email" name="email" id="emailid"><br><br>
<label for="num">Number</label>
<input type="number" name="number" id="num"><br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>Output

app.js
const express=require('express');
const app=express();
const port=8000;
app.use(express.urlencoded({extended:true}))
app.use(express.json())
app.get('/',(req,res)=>{
res.sendFile(__dirname+'/index.html')
})
app.post('/submit',(req,res)=>{
console.log("Post parameter are " + JSON.stringify(req.body));
res.redirect('/')
})
app.listen(port,()=>{
console.log(`Listening on ${port}`);
})
After Submitting the form we will get the data to the console with the help of middleware.
Output :
PS C:\Users\HP\Desktop\CODESPEEDY\RECIEVE POST PARAMETER IN EXPRESS> node app.js
Listening on 8000
Post parameter are {"name":"Aayush","email":"abc@gmail.com","number":"1234567890"}.
But if we want to send the data from the postman or some other platform by api platform then we want to add app.use(express.json()) which helps to parse json data and it is also inbuilt middleware function in express js.It parses incoming requests with JSON payloads ans is based on bodyparser.
Example
{
"name":"Aayush",
"email":"abc@gmail.com",
"password":"1234567890"
}
By this also same output will be there in console.
Leave a Reply