skip to Main Content

I have created a webpage to store user data into my MongoDB database using a html form. But I’m facing an issue because the form submission on my webpage is not triggering the expected POST request to my Express server.

HTML:

  <body>
        <main>
          <form id="profile-form" method="POST" action="/">
            <h2>BASIC INFORMATION</h2>
            <h5>NOTE: Fields with '**' are mandatory</h5>
            <label for="first-name">First Name**: </label><input id="first-name" name="FirstName" placeholder="Enter First Name" required><br>
            <label for="last-name">Last Name**: </label><input id="last-name" name="LastName" placeholder="Enter Last Name" required><br>
            <label for="email-id">Email**: </label><input id="email-id" name="Email" placeholder="Enter Mail ID" required><br>
            <label for="age">Age: </label><input id="age" name="Age" placeholder="Enter Age"><br>
            <label>Gender: </label>
            <select name="gender">
              <option value="select">Select</option>
              <option value="male">Male</option>
              <option value="female">Female</option>
              <option value="other">Other</option>
            </select><br>
            <label for="weight">Weight: </label><input id="weight" name="Weight" placeholder="Enter Weight (in Kg)"><br>
            <label>Height: </label><input id="foot" name="Feets" placeholder="Feet"><input id="inches" name="Inches" placeholder="Inches"><br>
            <label for="bmi">BMI: </label><input id="bmi" name="BMI" placeholder="Enter BMI"><br><br>
            <h2>BODY MEASUREMENTS</h2>
            <label for="waist">Waist: </label><input id="waist" name="Waist" placeholder="Enter Waist Size (in cms)"><br>
            <label for="chest">Chest: </label><input id="chest" name="Chest" placeholder="Enter Chest Size (in cms)"><br>
            <label for="hip">Hip: </label><input id="hip" name="Hip" placeholder="Enter Hip Size (in cms)"><br>
            <label for="thigh">Thigh: </label><input id="thigh" name="Thigh" placeholder="Enter Thigh Size (in cms)"><br>
            <label for="calf">Calf: </label><input id="calf" name="Calf" placeholder="Enter Calf Size (in cms)"><br>
            <button type="submit" class="btn btn-success">SUBMIT</button>
          </form>     
        </main>    
      <script src="data.js"></script>
  </body>

JavaScript(data.js):

const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const dot = dotenv.config();
const PORT = process.env.PORT || 5000;
const username = process.env.MONGODB_USERNAME;
const password = process.env.MONGODB_PASSWORD;

app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public'), { index: 'basic.html' }));

mongoose.connect(`mongodb+srv://${username}:${password}@cluster0.e6wowbu.mongodb.net/FITIFY_PROFILES?retryWrites=true&w=majority`);
const Profile = require('./profileModel');

app.post('/', (req, res) => {
  console.log("started");
  var uniqueId = Math.floor(Math.random() * 10000) + 1;
  req.body.gender = req.body.gender === "select" ? "Not Specified" : req.body.gender;
  const newProfileData = {
    uniqueCode: uniqueId,
    email: req.body.Email,
    firstName: req.body.FirstName,
    lastName: req.body.LastName,
    age: parseInt(req.body.Age) || 0,
    weight: parseFloat(req.body.Weight) || 0,
    bmi: parseFloat(req.body.BMI) || 0,
    height: 12 * parseInt(req.body.Feets) + parseInt(req.body.Inches) || 0,
    waist: parseFloat(req.body.Waist) || 0,
    chest: parseFloat(req.body.Chest) || 0,
    hip: parseFloat(req.body.Hip) || 0,
    thigh: parseFloat(req.body.Thigh) || 0,
    calf: parseFloat(req.body.Calf) || 0,
    gender: req.body.gender
  };

  Profile.create(newProfileData)
    .then(createdProfile => {
      console.log('Profile created:', createdProfile);
      res.send(`✅✅✅ SUCCESS!! PLEASE STORE YOUR UNIQUE FITIFY ID FOR FUTURE USE: <span style="color: gold; font-weight: bold; font-size: 25px;">${uniqueId}</span>. NOTE: NEVER SHARE THIS CODE WITH ANYONE!!`);
    })
    .catch(error => {
      console.error('Error creating profile:', error);
      res.send(`⚠️⚠️⚠️ ALERT!! ERROR IN STORING YOUR DATA: ` + error);
  });
});

app.listen(PORT, console.log("Server is listening on port: " + PORT));

NOTE: I have kept the username and password in a .env file and can assure you that they are correct.
I’ve verified that my Express server is running on the correct port (5000) and there are no error messages in the console. I’ve added a console.log statement inside the route handler for the POST request (app.post(‘/’)), but it’s not being triggered when I submit the form.

As a beginner in backend development I am clueless about this problem, Kindly help me find a solution to this issue.

2

Answers


  1. I’m curious if the HTML is a view that you are serving to the client or if it is a frontend framework that will communicate with your backend.

    Login or Signup to reply.
  2. action: The resource/URL where data is to be sent for processing when the form is submitted. If this is not set (or set to an empty string), then the form will be submitted back to the current page URL

    But the express server will serve/run from a different port. So the server doesn’t receive any requests while submitting the form.

    1. try to set reverse proxy to point out the express server
    2. Please refer to form and express post
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search