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

Express POST接口与前端GET请求不匹配致404错误求助

解决Express POST接口与React GET请求不匹配导致的404错误

核心问题:HTTP请求方法不匹配

你后端用router.post()定义了/get-all-doctors和/get-all-users接口,但前端用axios.get()发起请求。Express会严格区分不同HTTP方法的相同路径,因此找不到对应路由,返回404错误。

解决方案

方案1:后端改为GET请求(推荐,符合REST查询规范)

查询类接口用GET更合理,将后端路由的router.post()替换为router.get(),同时修正错误提示文案:

const express = require("express");
const router = express.Router();
const User = require("../models/userModel");
const Doctor = require("../models/doctorModel");
const authMiddleware=require('../middlewares/authMiddleware');

router.get("/get-all-doctors", authMiddleware, async (req, res) => {
  try {
    const doctors = await Doctor.find({});
    res
      .status(200)
      .send({
        message: "Doctors fetched successfully",
        success: true,
        data: doctors,
      });
  } catch (error) {
    console.log(error);
    res.status(500).send({
      message: "Error fetching doctors",
      success: false,
      error,
    });
  }
});

router.get("/get-all-users", authMiddleware, async (req, res) => {
  try {
    const users = await User.find({});
    res
      .status(200)
      .send({
        message: "users fetched successfully",
        success: true,
        data: users,
      });
  } catch (error) {
    console.log(error);
    res.status(500).send({
      message: "Error fetching users",
      success: false,
      error,
    });
  }
});
module.exports = router;

方案2:前端改为POST请求(若坚持使用POST)

将前端的axios.get()改为axios.post(),注意POST请求需传入空body参数:

const getUsersData = async () => {
  try {
    dispatch(showLoading()); // 修正拼写错误:dispatach → dispatch
    const response = await axios.post("/api/admin/get-all-users", {}, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem("token")}`,
      },
    });
    dispatch(hideLoading());
    if (response.data.success) {
      setUsers(response.data.data);
    }
  } catch (error) {
    dispatch(hideLoading());
  }
};

额外需要修正的细节

  1. 前端拼写错误:dispatach改为dispatch,否则Redux的loading状态无法正常触发
  2. 表格列字段不匹配:dataIndex: "created at"改为dataIndex: "createdAt"(mongoose默认创建时间字段为createdAt),可添加格式化逻辑:
{
  title: "Created At",
  dataIndex: "createdAt",
  render: (date) => new Date(date).toLocaleString()
}

验证步骤

  1. 重启后端服务,确保路由修改生效
  2. 清除前端缓存后重新测试请求
  3. 查看浏览器Network面板,确认请求方法、路径与后端路由完全匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 12:35:06