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

React使用Axios发POST请求到Node.js接口返回404错误如何解决

问题原因

你收到404报错的核心原因是:你的Express服务仅配置了GET方法的/getData接口,没有定义POST方法的同路径路由,Express无法匹配到POST请求的处理逻辑,就会返回404状态码。
另外你当前的服务端代码还有两个遗漏点:

  • 没有配置JSON请求体解析中间件,无法读取Axios POST发送的JSON格式数据
  • 返回的数组是硬编码在GET接口内的,无法新增存储你提交的新对象
修复方案

1. 调整服务端 server.js 代码

修改后的完整代码如下:

const express = require("express");
const app = express();
const cors = require('cors')

app.use(cors({
    origin: 'http://localhost:3000'
}))
// 新增:解析JSON格式的请求体
app.use(express.json())

// 把数据抽离为全局变量,方便POST接口新增内容
let dataList = [
    {
        "description": "",
        "durationday": "fullday",
        "end": "null",
        "id": 0,
        "location": "",
        "start": "null",
        "title": "",
    },
    {
        "description": "yaaa!",
        "durationday": "absent",
        "end": "10-04-2021 12:10:00",
        "id": 1,
        "location": "perth",
        "start": "10-04-2021 12:10:00",
        "title": "holiday",
    },
    {
        "description": "busy",
        "durationday": "fullday",
        "end": "10-22-2021 12:10:00",
        "id": 2,
        "location": "melbourne",
        "start": '10-19-2021 12:00:00',
        "title": "working",
    },
    {
        "description": "dd",
        "durationday": "halfday",
        "end": "10-24-2021 12:10:00",
        "id": 3,
        "location": "updated perth",
        "start": "10-24-2021 12:10:00",
        "title": "updated holiday",
    }
]

// GET接口返回数组
app.get('/getData', (req, res) => {
    res.json(dataList);
});

// 新增:POST接口接收提交的新数据,存入数组
app.post('/getData', (req, res) => {
    const newItem = req.body
    dataList.push(newItem)
    // 返回更新后的数组给前端
    res.json({
        code: 200,
        msg: '新增成功',
        data: dataList
    })
})

// 修正原来的笔误:pot改为port
app.listen(5000, () => console.log("Running on port 5000"))

2. 前端代码优化(可选,不影响运行)

你当前的请求代码同时用了async/await和.then/.catch,写法可以统一,调整后更易维护:

const sendData = async () => {
  try {
    const response = await axios.post('http://localhost:5000/getData', {
      description: "dd",
      durationday: "halfday",
      end: "10-24-2021 12:10:00",
      id: parseInt(344444),
      location: "updated perth",
      start: "10-24-2021 12:10:00",
      title: "updated holidayssssssssss",
    })
    console.log(response.data)
  } catch (error) {
    console.log(error)
  }
}
测试方法

修改完后重启Node服务,再点击前端的提交按钮,就可以正常提交数据,不会再出现404报错。

注意:当前数据是存在服务端内存中的,重启服务后新增的数据会丢失,如果需要持久化存储可以对接数据库或者本地文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:48:02