使用NodeJS+Express结合Fetch API时出现XHR POST 404错误求助
解决Fetch API POST请求404及后端无法接收数据问题
问题概述
使用前端Fetch API发送POST请求到http://localhost:5000/email时,持续返回404 Not Found错误,前端能正常获取表单数据,但后端无法接收。此前使用XHR也遇到相同问题。
错误原因分析
- POST路由语法错误:后端代码中
app.post("/email")后面多了一个右括号,导致路由未正确注册,这是404的核心原因。 - dotenv未初始化:
require("dotenv")未调用config()方法,无法加载环境变量,后续邮件发送会因缺少配置失败。 - res.sendFile使用不当:根路由
app.get("/")中多次调用res.sendFile,只有第一个会生效,且路径未使用绝对路径,可能导致静态文件无法正确返回。 - 未声明变量:
FromMailjs = req.body未声明变量,会污染全局作用域。 - 重复中间件:重复添加
app.use(express.json()),虽不影响功能,但冗余。
修复后的代码
后端代码
const express = require("express"); const path = require("path"); const app = express(); require("dotenv").config(); const Port = process.env.PORT || 5000; app.use(express.static("public")); app.use(express.json()); app.use( express.urlencoded({ extended: false, }) ); const nodemailer = require("nodemailer"); app.get("/", (req, res) => { res.sendFile(path.join(__dirname, "public", "index.html")); }); // 修复POST路由语法错误 app.post("/email", (req, res) => { const FromMailjs = req.body; console.log(FromMailjs); const transporter = nodemailer.createTransport({ auth: { user: process.env.Email, pass: process.env.Pass, }, }); const MailOptions = { from: req.body.Email, to: process.env.MyEmail, text: `${req.body.FirstName} ${req.body.LastName}\n电话: ${req.body.PhoneNumber}\n邮箱: ${req.body.Email}`, }; transporter.sendMail(MailOptions, (error, info) => { if (error) { console.log(error); res.status(500).send("error"); } else { console.log("Email sent"); res.send("success"); } }); }); app.listen(Port, () => { console.log(`listening on port ${Port}`); });
前端代码(补充错误处理)
const ContactForm = document.querySelector(".contact-form"); ContactForm.addEventListener("submit", async (e) => { e.preventDefault(); const FirstName = document.getElementById("Fname").value; const LastName = document.getElementById("Lname").value; const PhoneNumber = document.getElementById("PhoneNumber").value; const Email = document.getElementById("Email").value; const FormData = { FirstName, LastName, PhoneNumber, Email, }; const PostOptions = { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(FormData), }; try { const response = await fetch("/email", PostOptions); const result = await response.text(); console.log(result); // 可根据结果添加用户提示,如alert(result) } catch (error) { console.error("请求失败:", error); } });
额外说明
- 若使用Mailgun作为邮件服务商,需参考nodemailer官方文档补充
createTransport的对应配置项。 - 确保项目根目录下的
.env文件包含Email、Pass、MyEmail三个环境变量。
内容的提问来源于stack exchange,提问作者Aaarrnn
相关产品推荐
相关产品推荐

