Body parsing in Express JavaScript body-parser

Fetching data from a website using express is easier than node.js. Here we are going to fetch data from the website print to the console and this website will work on the port number 3000 ( choose any port number according to your convenient). Here we gonna learn how to do Body Parsing in express using body-parser.

Body Parsing in express using body-parser

Here in this code, I have created two pages with the URL ” /new-product” and “/product”. In a new-product page, there will be a form created through a method req.send() using HTML syntax. After submitting the form this website will redirect to a new page that has URL “/product” and data of webpage is print to console.

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser,urlencoded({extended :true});
app.get('/new-product',(req,res,next)=>{
     console.log("You are into /new-product");
     req.send("<form method="Post", action="/product"> <input type="text" name="msg"><br><button type ="submit">Click Here </button></form>")
      };
app.post('/product',(req,res,next)=>{
     console.log("You are into /new-product");
     console.log(req.body);
     req.send("The submission has done successfully");
     };
app.listen(3000);

When we call webpage new-product then a form will display having text field and submission button as shown below.

Output:

After submitting data, data will print to console using method console.log() and in the website, there will be a redirection to the product page and print “The Submission has done successfully” as shown below.

Output:
The submission has done successfully

app.listen() method to use to bind port number to the website. Here I assigned 3000 port number to the website.

Check out another post as well:



Leave a Reply

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