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

React项目与Express服务器根路径连接异常问题求助

问题:根路径代理导致React页面被覆盖,无法正常获取API数据

项目文件夹结构中,App.js和setupProxy.js位于client文件夹的src目录下。当前访问localhost:3000时,界面与localhost:5000完全一致,原本预期控制台打印键为"test"、值为"hi"的对象中"test"对应的值,但无法实现。将所有"/"路径改为/api这类非根路径时,功能可正常运行,询问为何无法使用"/"路径。

相关代码

[client > src > App.js]

import axios from "axios"
import { useEffect } from 'react'
import './App.css'

function App() {
  const callApi = async () => {
    axios.get("/").then((res) => console.log(res.data.test))
  }

  useEffect(() => {
    callApi()
  }, [])

  return <div>test</div>
}

export default App

[client > src > setupProxy.js]

const { createProxyMiddleware } = require("http-proxy-middleware")

module.exports = function(app) {
    app.use(
        createProxyMiddleware("/", {
            target: "http://localhost:5000",
            changeOrigin: true,
        })
    )
}

[server > Router > test.js]

const express = require('express')
const router = express.Router()

router.get('/', (req, res) => {
    res.send({ test: "hi" })
});

module.exports = router

[server > server.js]

const express = require('express')
const app = express()
const test = require('./Router/test')

app.use('/', test)

const PORT = 5000
app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`)
})

原因分析

当你用createProxyMiddleware("/", ...)配置代理时,所有发送到localhost:3000的请求都会被转发到localhost:5000,包括React开发服务器原本要处理的静态资源、入口HTML文件。

React开发服务器默认在根路径提供自己的index.html,现在这个请求被代理到了Express服务器,所以你看到的是Express返回的内容,而不是React的页面。同时,React组件代码都没正常加载执行,axios的请求逻辑自然也不会触发,导致控制台没有预期输出。

解决方案

最稳妥的方式是给API请求添加统一前缀,避免与React开发服务器的静态资源请求冲突:

  1. 修改代理配置:将setupProxy.js中的代理路径改为/api:
const { createProxyMiddleware } = require("http-proxy-middleware")

module.exports = function(app) {
    app.use(
        createProxyMiddleware("/api", {
            target: "http://localhost:5000",
            changeOrigin: true,
        })
    )
}
  1. 修改后端路由:

    • 在server.js中,将路由挂载路径改为/api:
      app.use('/api', test)
      
    • 在test.js中,保持router.get('/', ...)即可(因为已经挂载在/api下,实际接口路径为/api/)
  2. 修改前端请求:在App.js中,将axios请求路径改为/api:

axios.get("/api").then((res) => console.log(res.data.test))

这样配置后,只有/api开头的请求会被代理到Express服务器,React开发服务器会正常处理静态资源和页面请求,两者互不干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:06:22