React表单无法通过Express写入DATA.txt,报404错误求助
问题背景
尝试多种方法仍出现相同错误,修改文件路径无效。当前项目结构:
- nodemodules
- public
- src(包含App.jsx等所有文件)
- DATA.txt
- server.js
错误信息
App.jsx:33 Error submitting form: AxiosErrorcode: "ERR_BAD_REQUEST"config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}message: "Request failed with status code 404"name: "AxiosError"request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}response: {data: '\n\n\n<meta char…\n\n
Cannot POST /\n\n\n', status: 404, statusText: 'Not Found', headers: AxiosHeaders, config: {…}, …}stack: "AxiosError: Request failed with status code 404\n at settle (http://localhost:3000/static/js/bundle.js:42609:12)\n at XMLHttpRequest.onloadend (http://localhost:3000/static/js/bundle.js:41269:66)\n at Axios.request (http://localhost:3000/static/js/bundle.js:41770:41)\n at async handleSubmit (http://localhost:3000/static/js/bundle.js:50:7)"[[Prototype]]: Error) *
相关代码
server.js
const express = require("express"); const fs = require("fs"); const bodyParser = require("body-parser"); const app = express(); const PORT = 3000; app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.post("/", (req, res) => { const appData = req.body; fs.appendFile("data.txt", JSON.stringify(appData) + "\n", (err) => { if (err) throw err; }); res.send("Data has been successfully submitted!"); }); app.listen(PORT);
App.jsx
import React, { useState } from 'react'; import axios from 'axios'; const App = () => { const [appData, setAppData] = useState({ firstName: '', lastName: '', email: '', phoneNumber: '', country: '', paymentType: '' }); const handleChange = (e) => { const { name, value } = e.target; setAppData({ ...appData, [name]: value }); }; const handleSubmit = async (e) => { e.preventDefault(); try { await axios.post('/', appData); alert('Form submitted successfully!'); setAppData({ firstName: '', lastName: '', email: '', phoneNumber: '', country: '', paymentType: '' }); } catch (error) { console.error('Error submitting form: ', error); alert('Error submitting form. Please try again.'); } }; return ( <form onSubmit={handleSubmit}> <input type="text" name="firstName" value={appData.firstName} onChange={handleChange} placeholder="First Name" required /><br /> <input type="text" name="lastName" value={appData.lastName} onChange={handleChange} placeholder="Last Name" required /><br /> <input type="email" name="email" value={appData.email} onChange={handleChange} placeholder="Email" required /><br /> <input type="tel" name="phoneNumber" value={appData.phoneNumber} onChange={handleChange} placeholder="Phone Number" required /><br /> <input type="text" name="country" value={appData.country} onChange={handleChange} placeholder="Country" required /><br /> <select name="paymentType" value={appData.paymentType} onChange={handleChange} required> <option value="">Select Payment Type</option> <option value="Credit Card">Credit Card</option> <option value="PayPal">PayPal</option> <option value="Bank Transfer">Bank Transfer</option> </select><br /> <button type="submit">Submit</button> </form> ); }; export default App;
解决方案
1. 解决端口冲突
React开发服务器默认占用3000端口,和你的Express服务器端口重复,导致请求无法正确转发:
- 修改Express端口:将
const PORT = 3000;改为const PORT = 5000; - 配置React代理:在项目根目录的
package.json中添加"proxy": "http://localhost:5000",这样React会自动把API请求转发到Express服务器
2. 修正文件路径大小写
项目中是DATA.txt,但Express代码里写的是data.txt,区分大小写的系统(如Linux/macOS)会找不到文件,把fs.appendFile("data.txt", ...)改为fs.appendFile("DATA.txt", ...)
3. 调整异步写入逻辑
当前代码在文件写入未完成时就发送响应,可能导致写入失败但前端收到成功提示,修改为异步等待写入完成:
app.post("/", async (req, res) => { const appData = req.body; try { await fs.promises.appendFile("DATA.txt", JSON.stringify(appData) + "\n"); res.send("Data has been successfully submitted!"); } catch (err) { console.error(err); res.status(500).send("Failed to save data"); } });
4. 正确启动服务顺序
先启动Express服务器:node server.js,再启动React开发服务器:npm start
内容的提问来源于stack exchange,提问作者Michael Hamar

