Error 404 when Making POST Request to Express.js Server

I’m currently working on a web application using Express.js and encountering a 404 error when attempting to make a POST request to the server. I have a simple HTML form with a submit button that should send form data to the server for email processing. However, when I click the submit button, I receive a “404 Not Found” error in the browser’s console.

http://localhost:3000/collect-info 404 (Not Found).

I have already tried troubleshooting by checking the server logs, ensuring that the server is running, and verifying the route for handling POST requests. However, I’m unable to identify the root cause of the issue.

Tryied to add several console.log statements after – Submit button clicked.
and – Sending email… which is one step before >> fetch(‘/collect-info’ << the problematic line

The server log says nothing.
Also tried to shut the firewall, tried witth chrome and firefox.

Any assistance or insights into this problem would be greatly appreciated. Thank you in advance!

Here’s the relevant code:

<form action="/collect-info" method="post">
            <div>
                <label for="fname">First name:</label>
                <br>
                <input type="text" id="fname" placeholder="First name" name="fname" />
            </div>
            <div>
                <label for="lname">Last name:</label>
                <br>
                <input type="text" id="lname" placeholder="Last name" name="lname">
            </div>
            <div>
                <label for="mail">Email:</label>
                <br>
                <input type="email" id="mail" placeholder="Email" name="user_email" />
            </div>
            <div>
                <label for="country">Country:</label>
                <br>
                <input type="text" id="country" placeholder="Country" name="user_country" />
            </div>
            <div>
                <label for="level">Level:</label>
                <br>
                <input type="range" id="level" name="user_level" min="0" max="5" />
                <span id="level-indicator">Select your Level</span>
            </div>
            <div>
                <label for="msg">Message:</label>
                <br>
                <textarea id="msg" placeholder="Message" name="user_message"></textarea>
            </div>
            <div>
                <label for="submit"></label>
                <br>
                <input type="submit" value="Submit" id="submit-button">
            </div>
        </form>
        


        <script src="js/sendEmail.js"></script>
        <script src="js/script.js"></script>
function sendEmail(formData) {
    // Send form data to the server using the fetch API
    console.log("Sending email...");
    fetch('/collect-info', {  //THE BROWSER CONSOLE SAYS THAT THE PROBLEM IS IN THIS LINE
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(formData),
    })
      .then(response => response.text())
      .then(data => {
        console.log(data); // Handle the server's response, if needed
      })
      .catch(error => {
        console.error('Error:', error);
      });
  }
  
  document.addEventListener("DOMContentLoaded", function () {
    // Event listener for the submit button
    const submitButton = document.getElementById("submit-button");
  
    submitButton.addEventListener("click", function (event) {
      event.preventDefault();

      console.log("Submit button clicked.");
  
      // Gather form data
      const formData = {
        fname: document.getElementById("fname").value,
        lname: document.getElementById("lname").value,
        user_email: document.getElementById("mail").value,
        user_country: document.getElementById("country").value,
        user_level: document.getElementById("level").value,
        user_message: document.getElementById("msg").value
      };
  
      // Send the email using a client-side method (e.g., fetch)
      sendEmail(formData);
    });
  });
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const nodemailer = require('nodemailer');
const path = require('path');  
const bodyParser = require('body-parser');

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


app.use((req, res) => {
  res.status(404);
  res.send('<h1>Error 404: Resource not found</h1>')
})


app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

app.post('/collect-info', (req, res) => {
  // Access form data through req.body
  console.log('POST request received');
  const formData = req.body;

  // Create a transporter with Gmail SMTP settings
  const transporter = nodemailer.createTransport({
    service: 'gmail',
    auth: {
      user: '******@gmail.com', 
      pass: '***********', 
    },
  });

  // Create an email message
  const mailOptions = {
    from: '*******@gmail.com', 
    to: '*****@******', 
    subject: 'New Form Submission',
    text: `Name: ${formData.fname} ${formData.lname}\nEmail: ${formData.user_email}\nMessage: ${formData.user_message}`,
  };

  // Send the email
  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      console.error('Error sending email:', error);
      res.status(500).send('Error sending email');
    } else {
      console.log('Email sent:', info.response);
      res.send('Form submitted successfully!');
    }
  });
});

  • Can you screenshot and give the error? Also try going to the network tab and going to the request. All the details in the network tab request would be nice too!

    – 

Leave a Comment