向 Express.js 服务器发出 POST 请求时出现错误 404

问题描述 投票:0回答:1

我目前正在使用 Express.js 开发 Web 应用程序,并在尝试向服务器发出 POST 请求时遇到 404 错误。我有一个带有提交按钮的简单 HTML 表单,该按钮应将表单数据发送到服务器进行电子邮件处理。但是,当我单击提交按钮时,我在浏览器控制台中收到“404 Not Found”错误。

http://localhost:3000/collect-info 404(未找到)。

我已经尝试通过检查服务器日志、确保服务器正在运行并验证处理 POST 请求的路由来进行故障排除。但是,我无法确定问题的根本原因。

尝试在单击“提交”按钮后添加多个 console.log 语句。 并且 - 正在发送电子邮件...这是 >> fetch('/collect-info' << the problematic line

服务器日志什么也没说。 还尝试关闭防火墙,尝试使用 chrome 和 firefox。

对此问题的任何帮助或见解将不胜感激。预先感谢您!

相关代码如下:

<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!');
    }
  });
});
node.js express http-post http-status-code-404 fetch-api
1个回答
0
投票

您需要将

not-found
中间件放置在之后定义其余的应用程序路由。

在上面的代码示例中,请确保在回退到默认 404 处理程序之前首先定义路由 (

collect-info
)。否则,无论其他路由如何,所有请求都由 404 中间件处理。

// first define the route
app.post('/collect-info', (req, res) => {
 ...
});

// and then the not-found handler
app.use((req, res) => {
  res.status(404);
  res.send('<h1>Error 404: Resource not found</h1>')
})
© www.soinside.com 2019 - 2024. All rights reserved.