Handling Form Data POST request in Express

form_data_thumb

How to get form data using express js. POST form data and receive at the backend.

Install bodyParser

npm i body-parser

For parsing the form data, json , etc.

calculator.js

const express = require("express");
const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.urlencoded({extended: true }));  //extended for allowing to post nested objects

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("Result: "+ result);
});

app.listen(4000, function(){
    console.log("Server started at port 4000");
});

This image has an empty alt attribute; its file name is post-data-express-js.png

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator</title>
    <body>
        <h1> 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">Calculate </button>



        </form>

    </body>
</head>
<body>
    
</body>
</html>

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published.