What are some steps I can take to diagnose why my Express server is not receiving POST requests from my HTML form?

Struggling with an unexpected issue on my website where the form submission is not triggering the POST request to my Express server. I've set up a MongoDB database and created a HTML form to store user data, but something seems to be amiss.

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));

I've made sure my credentials in the .env file are accurate and checked that the Express server is running without any errors. However, the console.log statement in the route handler for the POST request is not being triggered upon form submission. Seeking guidance from experienced developers to help resolve this perplexing issue as a beginner in backend development.

Answer №1

I wonder if the HTML code is simply a view being sent to the user, or if it's part of a frontend framework that interacts with your backend systems.

Answer №2

When submitting a form, the action attribute specifies the resource or URL where the data will be sent for processing. If this is not set or set to an empty string, the form will default to submitting back to the current page URL.

However, it's important to note that if the express server is running on a different port, it may not receive any requests when the form is submitted.

  1. One solution is to try setting up a reverse proxy to direct traffic to the express server.
  2. For more information on handling GET and POST requests in Express 4, please refer to this guide.

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

Getting a specific element from an Ajax response may involve using JavaScript methods to target the desired

Within my PHP file, there are multiple HTML elements that I am fetching in an AJAX response. Currently, all these HTML elements are being returned in my drop area. How can I adjust the code to only retrieve a specific element, such as an image, like so: P ...

Utilize jQuery and AJAX to refresh functions after each AJAX call for newly added items exclusively

I have encountered an issue with my jQuery plugins on my website. Everything functions smoothly until I load new elements via AJAX call. Re-initializing all the plugins then causes chaos because some are initialized multiple times. Is there a way to only i ...

Clicking the button will trigger the onclick event

I'm working on a button component in TypeScript and I have encountered an issue with passing the event to the submitButton function. import * as React from 'react'; interface Props { className?: string; text: string; onClick?(event: Reac ...

Request the generic password prior to revealing the concealed div

I want to implement a feature where a hidden div is shown once a user enters a password. The password doesn't need to be stored in a database, it can be something simple like 'testpass' for now. Currently, I have written some code using Java ...

Comparing Nodewebkit and Electron: Which is the Right

I am currently exploring different paths to take. I need to establish a well-structured foundation, essentially a skeleton app that other developers can use as a starting point for coding. Here are the requirements: - Web application (SQL Server) - Deskto ...

Adjusting the input in a Textfield within React using Material UI

const [formData, setFormData] = useState({}); useEffect(() => { fetch("/formdata") .then((res) => res.json()) .then((data) => setFormData(data)); }, []); console.log("Form Data", formData); //Sorting by order let attr; ...

Store <td> in a variable

At the moment, I have a script that allows users to input an item name, along with its size, color, and other options. Each of these entries is saved as individual items with their custom specifications, such as a black t-shirt in large size. The script c ...

How to extract the parameters separated by slashes from a URL in Next.js

I need some guidance on how to redirect a URL in an express.js configuration. Here's the scenario: The URL is: profile/myname To forward to my page profile.js, I use the following code in my express.js config: server.get('/profile/:username&ap ...

Tips for validating form input upon submission in Angular 6

Within my Angular application, I have successfully implemented form validators. However, I am aiming to trigger form validation specifically upon submission. This means that when the user clicks on the submit button and the form is invalid, the errors indi ...

IE8 - "object does not exist or is undefined" error

Below is the HTML code snippet: <td style="vertical-align: bottom;"><div id="resultCount">n.v.</div></td> Accompanied by this JavaScript code: function processResultCount(data) { $("#resultCount").html(formatNumber(data.res ...

Can you explain the compatibility between comet and PHP?

As I utilize Comet iframe, I simply send script tags from the backend PHP file to the frontend where JavaScript displays them. I would appreciate it if someone could provide a concise explanation of how the comet server fits into the equation and how comm ...

The instance is referencing the property or method "sendResetMail" during render, but it is not defined

I'm pretty new to Vue and struggling with an error message while trying to get a reset email modal working in my Vue project: The error says that the property or method "sendResetMail" is not defined on the instance but referenced during render. I ...

What are the benefits of storing dist in both a GitHub repository and on npm?

I'm curious about why some repositories include a dist folder. Shouldn't repositories just store source code and not any builds or compiled files? Let's take a look at an example with ES6 code. package.json { "files": [ "dist", ...

Obtain offspring from a parent element using jQuery

$(document).ready(function() { $.ajax({ type: "POST", url: 'some/url', data: { 'name':'myname' }, success: function (result) { var result = ["st ...

Updating token using an Ajax request in a PHP webpage

Currently, I am encountering an issue with my token system for requesting PHP pages via Ajax. The problem arises when attempting to make multiple Ajax requests from the same page as I am unable to refresh the token on the initial page. To elaborate furthe ...

Looping through data in Vue.js with a specific condition

There is an object structured like this: groupedContacts: { 4: [ {name: 'foo'}, {name: 'bar'} ], 6: [ {name: 'foo bar'}, ] } Additionally, we have another array: companyList.models: models: [ ...

Is it possible in PHP to automatically retrieve all data posted through POST and uncheck multiple checkboxes simultaneously?

Hey everyone, I could really use some assistance. I'm attempting to utilize this code to dynamically retrieve variables and values from a form. However, the form contains numerous checkboxes that may or may not be checked. I'm looking for a way ...

Can "Operator" be used as a function parameter?

Take a look at this code snippet: const myFunction = (x, y, z) => { //Some code here }; $('whatever').on( event, function(){ myFunction( event.originalEvent && event.originalEvent.target ); //What is this operator doing? }); Can yo ...

Tips on resolving the flickering issue in dark mode background color on NextJS sites

One problem I am facing is that Next.js does not have access to the client-side localStorage, resulting in HTML being rendered with or without the "dark" class by default. This leads to a scenario where upon page reload, the <html> element momentari ...

What is the solution for the red underline issue with the @json Blade directive in VSC?

Everything seems to be functioning correctly with these variables, but I'm curious as to why they are underlined in red. Does anyone have a solution for this issue? https://i.sstatic.net/mzlkY.png Error message https://i.sstatic.net/4LajF.png ...