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

React组件无法从server.js获取数据的问题求助

前后端连接问题:React无法从Express后端获取数据

项目背景

正在开发个人项目,目标是让ChatGPT每日为用户生成写作提示,用户可撰写回应。目前刚学习React和Express,尝试通过Test.jsx组件从server.js获取示例提示并展示,但始终遇到数据获取失败问题。

前端代码(Test.jsx)

import React, { useState, useEffect } from "react";
import axios from "axios";
export default function Test() {
  const [textPromptback, setPromptback] = useState("hello");

  useEffect(() => {
    axios
      .get("https://localhost:5000/api")
      .then((response) => {
        setPromptback(response);
      })
      .catch((error) => {
        console.error("Error fetching prompt:", error);
      });
  }, []);

  return <div>{textPromptback}</div>;
}

后端代码(Server.js)

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

// Use a different route name like "/api/writing-prompt"
app.get('/api', (req, res) => {
  const prompt = 'This is a prompt fetched from the backend';
  res.json({prompt});
});

app.listen(5000, () => {
  console.log('Server started on port 5000');
});

报错信息

最初的错误:

Error fetching prompt: AxiosError
(anonymous) @ Test.jsx:13
:5000/api:1     Failed to load resource: net::ERR_CONNECTION_REFUSED
Test.jsx:13 Error fetching prompt: AxiosError
(anonymous) @ Test.jsx:13
:5000/api:1     Failed to load resource: net::ERR_CONNECTION_REFUSED

添加proxy配置后的错误:

GET https://localhost:5000/api net::ERR_CONNECTION_REFUSED
dispatchXhrRequest @ xhr.js:251
xhr @ xhr.js:49
dispatchRequest @ dispatchRequest.js:51
request @ Axios.js:148
Axios.<computed> @ Axios.js:174
wrap @ bind.js:5
(anonymous) @ Test.jsx:7
commitHookEffectListMount @ react-dom.development.js:23150
invokePassiveEffectMountInDEV @ react-dom.development.js:25154
invokeEffectsInDev @ react-dom.development.js:27351
commitDoubleInvokeEffectsInDEV @ react-dom.development.js:27330
flushPassiveEffectsImpl @ react-dom.development.js:27056
flushPassiveEffects @ react-dom.development.js:26984
(anonymous) @ react-dom.development.js:26769
workLoop @ scheduler.development.js:266
flushWork @ scheduler.development.js:239
performWorkUntilDeadline @ scheduler.development.js:533

尝试过的操作

  • 在React项目的package.json中添加"proxy": "https://localhost:5000"
  • 移除Test.jsx中axios.get里的https://localhost:5000,改为axios.get("/api")

解决方案步骤

1. 确认后端服务正常启动

  • 检查终端是否显示Server started on port 5000,未启动则执行node server.js启动后端
  • 若启动报错,执行npm install express cors确保依赖安装完整

2. 修正协议配置

后端默认使用http协议,需将前端请求和proxy配置中的https改为http:

  • 直接请求时:axios.get("http://localhost:5000/api")
  • 使用proxy时,package.json配置改为"proxy": "http://localhost:5000",同时前端请求改为axios.get("/api")

3. 修正状态更新逻辑

后端返回的是{prompt: "xxx"}格式数据,直接赋值整个response对象会导致渲染异常,需提取对应字段:

.then((response) => {
  setPromptback(response.data.prompt);
})

4. 端口冲突排查

确认5000端口未被其他程序占用,或更换后端端口(比如改为5001),同步修改前端请求的端口号

5. 跨域配置加固(可选)

若仍存在跨域问题,可指定允许的前端域名:

app.use(cors({
  origin: "http://localhost:3000" // React默认启动端口
}));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 01:09:54