calculator app using node express

 Calculator App


Q. How to get form data in express server?

Ans: Use Body-Parser Module to get html form data into the server.

    Example: 



app.get("/", function(req, res){
    res.sendFile(__dirname+"/index.html");
});

app.post("/", function(req, res){
    res.send("Data sent !");
});


If we wanna try to get from data we get form values in PayLoad section in Chrome Developer Tool



                Here we can see :

                firstNumber : 2

                secondNumber: 6

                these numbers are bound to forms input fields

To use these information in server We Need BodyParser

    > npm install body-parser

Then include it in your code:

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

Then use it:

       > app.use(bodyParser.urlencoded({extended: true}));

here urlencode() is function which give form data.


IF we console the request like this :

app.post("/", function(req, res){
    console.log(req.body);
    res.send("Data sent !");
});

Then we get output like : { firstNumber: '7', secondNumber: '1' }

To get individual values, Use: 

   
console.log(req.body.firstNumber); //get input field data of name firstNumber


So the complete code for calculator will be like this : 


app.post("/", function(req, res){
    // console.log(req.body.firstNumber);
    var num1 = req.body.firstNumber;
    var num2 = req.body.secondNumber;
    var result = num1+num2;
    res.send("The sum of " +num1+ " and " +num2+ " is : "+result);
});

and if num1 = 2 and num2 = 5 the output will be 25 because + sign here concatenate and thinks it Strings value.


So we have to parse it as a number. use parseInt() function.


app.post("/", function(req, res){
    // console.log(req.body.firstNumber);
    var num1 = parseInt(req.body.firstNumber);
    var num2 = parseInt(req.body.secondNumber);
    var result = (num1+num2);
    res.send("The sum of " +num1+ " and " +num2+ " is : "+result);
});




Comments

Popular posts from this blog

Setup node framework | Express

React for Beginners