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

React路由与Express路由冲突:访问/api/users返回404的解决方法

解决访问API路由返回React 404页面的问题

问题原因

Express的路由匹配规则是从上到下依次匹配,你当前的代码中,匹配所有GET请求的通配路由app.get('/*')定义在API路由(/api/users、/api/register)之前,导致所有请求(包括API请求)都会先被这个通配路由捕获,返回React的index.html文件。之后React的前端路由无法识别/api/users这个路径,就渲染了404页面。

解决方案

将所有API路由的定义移到通配路由app.get('/*')的前面,这样Express会优先匹配API路由,只有当请求不匹配任何API接口时,才会进入SPA fallback路由,返回index.html让React处理前端路由。

修改后的后端index.js代码

const express = require('express')
const mysql = require('mysql');
const path = require('path')

const app = express()
app.use(express.static(path.join(__dirname + "/public")))
app.use(express.json())

const PORT = 5000
app.listen(PORT)

// 先定义所有API路由
const db = mysql.createConnection({
    user: "root",
    host: "localhost",
    password: "",
    database: "project_db",
});

const users =
[
    { id: 1,name: "Andrew" },
    { id: 2, name: "Steve" },
    { id: 3, name: "John" },
    { id: 4, name: "Michael" },
    { id: 5, name: "Christian"  }
];

app.get("/api/users", (req, res) => {
    res.json(users);
})

app.post("/api/register", (req, res) => {
    const username = req.body.username;
    const password = req.body.password;
    const email = req.body.email;
    
    // 添加错误处理避免未捕获异常
    db.query("INSERT INTO users (name, password, email) VALUES (?, ?, ?)", [username, password, email], (err) => {
        if (err) {
            return res.status(500).send({ message: "注册失败", status: 0 });
        }
        res.send({
            "message": "account registered",
            "status": 1,
        });
    });
})

// 最后定义SPA fallback路由
app.get('/*', function(req, res) {
    res.sendFile(path.join(__dirname, '/public/index.html'), function(err) {
        if (err) {
            res.status(500).send(err)
        }
    })
})

额外注意事项

  • 确保express.json()中间件在API路由之前,这样才能正确解析POST请求的JSON请求体。
  • 数据库操作建议添加错误处理回调,避免未捕获的错误导致服务器异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 19:50:11