You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Node.js项目中Axios POST请求出现Network Error但数据已提交

解决Axios POST请求成功但触发Network Error的问题

核心问题:表单默认提交行为中断请求

你的按钮是type="submit",点击后会触发表单的默认提交逻辑——页面刷新,这会直接中断还在处理中的Axios请求,导致前端抛出Network Error。虽然后端已经完成数据写入,但请求被提前终止,所以进入了catch分支。

具体修复步骤

1. 阻止表单默认提交行为

在AddToList函数开头添加e.preventDefault(),彻底阻止页面刷新:

const AddToList = async (e) => {
    e.preventDefault(); // 关键:拦截表单默认提交动作
    const headers = {
        Accept: 'application/json, text/plain, */*',
        'Content-Type': 'application/json',
    }

    try {
        const response = await axios.post(
            "http://localhost:3001/addToList", 
            { event: 'random test', finished: true }, 
            { headers }
        );
        console.log(response);
    } catch (err) {
        console.log(err.response || err.message);
    }
}

另外建议统一用try/catch配合await的写法,比混合使用then/catch更清晰易读。

2. 优化后端异步逻辑(可选但推荐)

后端里fs.writeFile是回调式异步API,你没有等待文件写入完成就返回了响应,虽然不影响当前的Network Error,但可能出现“前端收到成功响应,但实际数据写入失败”的情况。建议换成Promise版本的fsPromises.writeFile并等待完成:

addToList: async (req, res) => {
    try {
        const data = await fsPromises.readFile('./Database/data.json');
        const dbResult = JSON.parse(data.toString()); // JSON.parse是同步操作,不需要await

        const newUser = {
            id: parseInt(dbResult.length) + 1,
            event: req.body.event,
            finished: req.body.finished,
        };

        dbResult.push(newUser); // push是同步方法,不需要await
        const dataStringify = JSON.stringify(dbResult);

        await fsPromises.writeFile('./Database/data.json', dataStringify); // 等待文件写入完成
        console.log("new data added");

        res.json({ msg: 'success, trying to fix Pending HTTP Axios err' });
    } catch (err) {
        console.log('error:', err);
        res.status(500).json({ msg: 'failed to add data' }); // 错误时返回500状态码,让前端感知异常
    }
}

同时添加全局try/catch,避免未处理的异常导致服务器崩溃。

3. 确认CORS配置(无需修改)

你的后端已经配置cors({origin: '*'}),Postman能正常请求也验证了CORS没有问题,这部分无需调整。

内容的提问来源于stack exchange,提问作者LearningToProgram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 11:03:12