Ayush Kumar
Ayush Kumar

Reputation: 11

Why I am getting this error in nodejs+express js

I am trying to calculate BMI

and it's giving me this error

Your BMI is NaN...I am using nodejs + expressjs

here is my js code

const express =  require("express");

const app  =  express();


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


app.post("/", function(req, res){
    var weight = parseInt("req.body.weight");
    var height = parseInt("req.body.height");

    var bmi = weight / (height * height);

    res.send("Your BMI is " + bmi);

});

app.listen(3000, function(){
    console.log("Server Started at Port 3000");
});

and here is my html code

<!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>BMI Calculator</title>
</head>
<body>
    <h1>BMI Calculator</h1>
    <form action="/" method="post">
        <input type="weight" name="weight" placeholder="Please type your weight">;
        <input type="height" name="height" placeholder="Please type your height">;
        <button type="submit">Calculate</button>
    </form>
</body>
</html>

A help would be appreciated

Upvotes: 0

Views: 43

Answers (2)

lpizzinidev
lpizzinidev

Reputation: 13284

Try to change your post middleware method like this:

app.post("/", function(req, res){
    const { weight, height } = req.body;
    var bmi = Number(weight) / (Number(height) * Number(height));

    res.send("Your BMI is " + bmi);
});

Upvotes: 1

Dave Yu
Dave Yu

Reputation: 412

"req.body.weight" should be without "s.

var weight = parseInt("req.body.weight");
var height = parseInt("req.body.height");

Here you parsed a int from a string literally called 'req.body.weight'

Thus, you get Not a Number as an output

Upvotes: 0

Related Questions