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

React前端提交博客表单时请求后端出现404错误的问题排查

博客应用表单提交404错误排查

我正在开发一个基础博客应用,需要获取标题(title)和文章内容(post)输入,通过表单提交将数据存入后端数据库。目前用React结合axios实现功能,但提交时出现404错误,相关代码及错误信息如下:

前端React代码

import React, { useState } from "react";
import axios from "axios";

const CreatePost = () => {
  const [title, setTitle] = useState("");
  const [post, setPost] = useState("");

  const onChangeTitle = (e) => {
    setTitle(e.target.value);
  };

  const onChangePost = (e) => {
    setPost(e.target.value);
  };

  const onSubmit = (e) => {
    e.preventDefault();
    const newPost = {
      title: title,
      post: post,
    };
    console.log(newPost);
    axios("http://localhost:5000/add", newPost)
      .then((res) => console.log(res.data))
      .catch((err) => console.log(err));
  };
  return (
    <form onSubmit={onSubmit} className="container">
      <div className="mb-3">
        <label className="form-label">Title</label>
        <input onChange={onChangeTitle} className="form-control"></input>
      </div>
      <div className="mb-3">
        <label className="form-label">Write Post</label>
        <textarea
          onChange={onChangePost}
          className="form-control"
          rows="15"
        ></textarea>
      </div>
      <button type="submit">POST</button>
    </form>
  );
};
export default CreatePost;

后端POST接口代码

app.post("/add", (req, res) => {
  const title = req.body.title;
  const post = req.body.post;
  const newPost = new Post({ title, post });
  newPost
    .save()
    .then(() => res.json("Post added"))
    .catch((err) => res.status(400).json("Error:" + err));
});

错误信息

GET http://localhost:5000/add 404 (Not Found)
AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}

问题原因及修复方案

核心问题

错误日志明确显示发送的是GET请求,但后端只注册了POST方法的/add接口,因此服务器找不到对应路由,返回404。

这是因为你调用axios的方式有误:直接传入URL和数据对象时,axios默认使用GET请求,数据会被当作URL参数处理,而非POST请求体。

修复步骤

  1. 修正axios请求方式:明确指定使用POST方法发送请求,将数据作为请求体传递:

    // 方式一:使用axios.post快捷方法
    axios.post("http://localhost:5000/add", newPost)
      .then((res) => console.log(res.data))
      .catch((err) => console.log(err));
    

    或者用配置对象的写法:

    // 方式二:完整配置请求参数
    axios({
      method: 'post',
      url: 'http://localhost:5000/add',
      data: newPost
    })
    
  2. 额外检查项:

    • 确认后端服务正常运行在localhost:5000,无端口冲突或防火墙拦截;
    • 后端需配置JSON请求体解析中间件(如Express的express.json()),否则req.body会为空,导致数据库保存失败:
      // 放在所有路由定义之前
      app.use(express.json());
      
    • 前端表单输入框建议添加name属性(如<input name="title" .../>),符合HTML表单规范,也便于后续扩展。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 04:18:30