Express.js post method malfunctioning for BMI calculation

Currently, I am working on a BMI calculator application in JavaScript as part of my practice. The app is supposed to take two inputs - weight and height, calculate the BMI, and display the result on the web page. However, after inputting the data and submitting, the calculated BMI does not show up on the webpage. In the DevTools network tab, I noticed that the request method shows as 'GET'. I have included the relevant code snippets below for reference. Any assistance would be greatly appreciated!

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

const app = express();
app.use(bodyParser.urlencoded({extended: true})); // used for handling data from HTML forms

// Home route for the calculator
 app.get("/", (req, res)=>{
     res.sendFile(__dirname+"/index.html");  // Send index.html as a response using res.sendFile method 
 })

 // Processing POST request for the calculator
 app.post("/", (req, res)=>{
    var num1 = Number(req.body.num1);
    var num2 = Number(req.body.num2);
    var total = num1 + num2;
    res.send(`<h1>The total is ${total}</h1>`);
 })

 // Route for GET request for the BMI calculator
 app.get("/bmicalculator", function(req, res){
     res.sendFile(__dirname+"/BMIcalculator.html");
 })

// Processing POST request and returning the calculated BMI
app.post("/bmicalculator", function(req, res){
    var weight = parseFloat(req.body.weight);
    var height = parseFloat(req.body.height);
    var BMI = weight / Math.pow(height, 2);
    console.log(BMI);
    res.send(BMI);
})

app.listen(3000, ()=>{
    console.log("Server is listening at port 3000");
})
<!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 style="background-color: darkkhaki;">
    <h1>Calculate Your BMI</h1>
    <form action="/bmicalculator" method="post"></form>
    <input type="text" name="weight" placeholder="Enter your weight">
    <input type="text" name="height" placeholder="Enter your height in meters">
    <button type="submit" name="Submit">Calculate BMI</button>
    
</body>
</html>

Answer №1

Make sure to enclose your INPUT elements within a FORM element so that the request is sent to the server and you can receive a response.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to enter NaN in Vue3?

Is there a way to handle NaN values and keep a field blank instead when calculating margins with a formula? https://i.stack.imgur.com/JvIRQ.png Template <form> <div class="row"> <div class="mb-3 col-sm ...

Troubleshooting Cross-Origin Resource Sharing (CORS) problem between React and Node/Express when integrating Google

I am facing a challenge with my React application where I am attempting to integrate a Node/Express/MySQL backend with OAuth. The React app is running on localhost:3000 while the Express server is on localhost:4000. In order to direct requests to the serve ...

Is there a method for executing ng-serve alongside expressjs?

I am currently following an Angular6/Express tutorial. In the tutorial, they utilize the following scripts: "scripts": { "ng": "ng", "start": "ng build && node ./bin/www", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e ...

Element on webpage "Expands" When Scrolled into Visibility

After posting a question on Stack Overflow, I noticed discrepancies between the element dimensions reported by Chrome Inspector and Selenium WebDriver. While Chrome Inspector showed w = 979, h = 1961, Selenium returned dimensions of 979 and 1461 respective ...

Troubles with proper functionality of antd's DatePicker.RangePicker within a React Function Component

I am currently utilizing React and the antd library, attempting to incorporate the DatePicker.RangePicker into my project. Initially, when I directly embed the RangePicker within the component, everything works smoothly. However, for better code organizat ...

Revamp the Design Layout of a Drag-and-Drop Tool

After experimenting with a drag and drop feature using jQuery, I discovered the following useful code snippet. Here's how it functions: $( "#sortable1, #sortable2" ).sortable({ connectWith: ".connectedSortable" }).disableSelection(); #so ...

What is the best way to show a message of success once the user has been redirected to the homepage?

Currently, I have a registration form utilizing AJAX and PHP for validation. Error messages can be displayed on the registration page if the user does not correctly fill out the form. Upon successful registration, the user is redirected back to the home pa ...

Arranging a list of objects with a designated starting value to remain at the forefront

Consider the array and variable shown below: array = ['complete','in_progress','planned']; value = 'planned'; The goal is to always sort the array starting with the 'value' variable, resulting in: array ...

VueJS and express implement CSRF token handling for secure POST requests

For my web application, I am using VueJS (cli 3) with axios for the front-end and NodeJS with ExpressJS for the back-end. Currently, I am working on securing the post user edit functionality by implementing CSRF tokens. In my Vue component (edit user), th ...

Measure the loading times of external web pages using JavaScript

I am seeking a minimalist approach to create a webpage on my server that utilizes JavaScript to calculate the loading time of the login page on various remote URLs/servers. These servers are dispersed globally, and my aim is to determine the quickest one f ...

Is there a way to retrieve a different value within the JavaScript code (imagepicker)?

I need help with setting up a page where users can choose an image to forward them to another page. However, I'm facing an issue when the user chooses two images at once. Can anyone provide ideas on how to handle forwarding in this scenario? You can c ...

The URL for this page is not within the app's designated domains and will not open Facebook Dialogs (FB UI)

I am currently working on integrating Facebook UI Dialogs into my website. My goal is to add custom actions when users share a post from my site. I have created my app, added the app URL and domain (which is the same as the URL), and included all necessa ...

For the past two days, there has been an ongoing issue that I just can't seem to figure out when running npm start

After multiple failed attempts, I have exhausted all troubleshooting steps including executing npm clear cache --force, deleting node_modules/ and package-lock.json, followed by running npm install, npm build, and eventually npm run dev. The errors encoun ...

Using Javascript with the Google Calendar API: How can I swiftly make a new event with the Quick Add feature?

Currently, I am exploring the Google Calendar API and struggling with implementing a Quick Add Event using javascript. Is it possible to achieve this task? Are there any resources or examples that can help me understand how to do it? My issue lies in the ...

Is it possible to call componentDidMount() multiple times in React?

I am in the process of converting an HTML API to ReactJS. The original HTML API is as follows: <script src="//dapi.kakao.com/v2/maps/sdk.js?appkey=3199e8f198aff9d5aff73000faae6608"></script> <script> var mapContainer = document.getE ...

Is the Vue2 Template compiler malfunctioning?

When compiling my code using webpack(^5.51.1) and vue-loader(^17.0.0), I encountered an issue while trying to run an older project. The error message displayed is as follows: [webpack-cli] Failed to load '/var/www/webpack.config.js' config [webpa ...

Stripping CSS from my HTML using TinyMCE

I have created a custom Javascript function that retrieves the content of an HTML file from my server and then integrates it into a TinyMCE editor. Here is the function: function LoadTemplate(url) { $.post(url, function (data) { // Access the ...

Guide on sorting an array within a specific range and extracting a sample on each side of the outcome

I need a simple solution for the following scenario: let rangeOfInterest = [25 , 44]; let input = [10, 20, 30, 40, 50, 60]; I want to extract values that fall between 25 and 44 (inclusive) from the given input. The range may be within or outside the inpu ...

Selenium - Activating a flash button

Currently, I am facing an issue while trying to load a URL using Selenium on Mozilla browser. The webpage contains a 'Login' button created in flash that I need to click on. I have explored the following resources: 1.How to click an element in Se ...

"Use jquerytools to create a dynamic play/pause button functionality for scrollable content

Greetings! I am currently working on creating a slide using Jquerytools. Here are some helpful links for reference: To view the gallery demonstration, please visit: For information on autoscroll functionality, check out: If you'd like to see my cod ...