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

React前端连接Express(MongoDB)后端出现连接拒绝错误求助

问题排查与解决方案

1. 协议不匹配导致连接拒绝

你前端fetch用了https://localhost:5000,但本地Express服务器默认跑的是http协议——你直接访问浏览器用的也是http,换https肯定连不上。把请求地址改成http://localhost:5000/api/projects/。

2. Fetch响应处理错误

Fetch API的响应对象没有.data属性,这是Axios的用法。正确的解析流程是先调用.json()把响应转成JSON:

fetch("http://localhost:5000/api/projects/", {
  method: "GET",
})
  .then((res) => res.json()) // 先解析响应体为JSON
  .then((data) => console.log(data)) // 这里才是拿到的数据
  .catch((e) => {
    console.error(e)
  })

3. 确认CORS配置是否生效

如果已经装了cors包,检查服务器端代码是否正确挂载了中间件:

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

// 开发环境可以直接允许所有来源
app.use(cors());

// 生产环境记得指定前端域名,比如React默认的3000端口
// app.use(cors({ origin: 'http://localhost:3000' }));

// 挂载你的项目路由
app.use('/api/projects', projectRouter);

app.listen(5000, () => {
  console.log('服务器运行在 http://localhost:5000');
});

4. 检查端口与服务器状态

  • 确认5000端口没被其他程序占用,服务器启动时控制台能看到服务器运行在 http://localhost:5000的日志。
  • 如果端口被占,要么杀掉占用进程,要么把Express服务器改成其他端口(比如5001),同时前端请求地址也要对应修改。

5. 可选:React代理配置

不想在前端写完整URL的话,在React项目的package.json里加一行代理配置,自动转发请求到后端:

"proxy": "http://localhost:5000"

之后前端请求可以简化成:

fetch("/api/projects/")
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.error(err))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 12:48:25