0

Can anyone help me with this Express js code?

<-- I am a beginner learning express js and I am trying to make a BMI calculator which result is computed in my localhost:3000/bmicalculator (server) Everything works fine but the result(var) BMI returns NaN BMI is nothing but a body mass index (simple formula) BMI formula = weight/height*height --> <--bimCalculator.html--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>BIM Calculator</title> </head> <body> <h1>BIM Calculator</h1> <form action="/bmicalculator" method="post"> <input type="text" name="height" placeholder="height"/> <input type="text" name= "weigth" placeholder="weigth"> <button type="submit">Calulate BIM</button> </form> </body> </html> //calculator.js below const express = require("express"); const bodyParser = require("body-parser"); //2. Bodypasser const app = express(); app.use(bodyParser.urlencoded({extended: true})); //BIM Calculator app.get("/bmicalculator", function(req, res){ res.sendFile(__dirname + "/bmiCalculator.html"); }); //post app.post("/bmicalculator",function(req,res){ var h=parseFloat(req.body.height); var w=parseFloat(req.body.weight); var bmi = w/(h*h); res.send("The BIM is "+ bmi); //bmi returns NaN which is the problem }); app.listen(3000, function(){ console.log("Successfull Sandesh on 3000"); });

30th May 2021, 12:03 PM
Sandesh Adhikari
Sandesh Adhikari - avatar
5 Respuestas
+ 2
Try logging out each of your variables from your result bit by bit. That way you will see which of the calculations might return NaN (NaN is basically saying that your result is returning something that is Not a Number) If this doesn't work you could also try to console.log just the resulting object in which you mighg be able to address the issue better.
1st Jun 2021, 1:37 PM
Leo
Leo - avatar
0
Leo okay so how do I console bit by bit🤔
1st Jun 2021, 3:14 PM
Sandesh Adhikari
Sandesh Adhikari - avatar
1st Jun 2021, 3:14 PM
Sandesh Adhikari
Sandesh Adhikari - avatar
0
Sandesh Adhikari console.log("height = " + h); console.log("h * h = " + h*h); console.log("weight = " + w); and even: console.log("bmi = " + bmi); anyway, why doing this basic computation on server side? it would be more efficient to compute it at client side ;P
1st Jun 2021, 4:30 PM
visph
visph - avatar
0
Sandesh Adhikari You can log your bit by bit as follows (according to your code example): // Your variables var h = parseFloat(req.body.height); var w = parseFloat(req.body.weight); var bmi = w/(h*h) // Testing the result by logging it console.log(req) // If the request object logs with your width and height correctly, then proceed to the next tests below console.log(w) console.log(h) console.log(bmi) By testing these you will be able to see what is happening in the process.
2nd Jun 2021, 6:24 AM
Leo
Leo - avatar