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

React+Express应用中Fetch无法获取Node接口返回数据的问题

解决React前端无法获取Express后端响应的问题

我来帮你排查并解决这个问题,看了你的代码后,主要有几个关键问题导致你拿不到后端返回的数据:

1. 错误的请求路径

你的后端接口是/weather,但前端请求的URL是http://localhost:3001?address=xxx,没有带上/weather路径,这会导致后端无法匹配到对应的路由,自然返回不了你期望的数据。

2. 误用mode: 'no-cors'

当你设置mode: 'no-cors'时,浏览器会限制你读取响应的内容(这就是为什么response.data和response.body都是空的),因为这个模式仅适用于不需要读取响应的情况(比如嵌入静态资源)。对于需要和后端交互获取数据的场景,你应该使用默认的cors模式(可以直接省略这个配置)。

3. 未正确解析响应数据

Fetch API的response对象并不是直接的返回数据,你需要调用response.json()来解析后端返回的JSON格式数据,这个方法返回一个Promise,你需要在后续的.then()中处理解析后的结果。

4. 缺少跨域(CORS)配置

由于React和Express运行在不同的端口(通常前端3000,后端3001),浏览器会触发跨域限制,你需要在后端配置CORS中间件来允许前端的请求。


现在来修改你的代码:

前端React的App.js修改:

// 修正请求路径,加上/weather接口
const url = `http://localhost:3001/weather?address=${this.state.location}`;
fetch(url) // 去掉mode: 'no-cors',使用默认的cors模式
  .then((response) => {
    // 先检查响应是否成功
    if (!response.ok) {
      throw new Error('请求失败,请稍后重试');
    }
    // 解析JSON格式的响应数据
    return response.json();
  })
  .then((data) => {
    // 这里就能拿到后端返回的数据了
    console.log(data);
    // 处理错误信息或业务数据
    if (data.error) {
      console.error('错误信息:', data.error);
    } else {
      console.log('温度:', data.temperature);
      console.log('湿度:', data.humidity);
      console.log('地点:', data.place);
    }
  })
  .catch((error) => {
    // 捕获网络错误或解析错误
    console.error('请求出错:', error);
  });

后端Node的app.js修改:

首先安装cors中间件:

npm install cors

然后在代码中引入并使用:

const express = require('express');
const cors = require('cors'); // 引入cors
const app = express();

app.use(cors()); // 启用CORS,允许所有来源的请求(开发环境可以这么用,生产环境建议配置具体来源)

app.get('/weather', (req, res) => {
  if (!req.query.address) {
    return res.send({ error: 'Please, provide an address' });
  }
  geoCode(req.query.address, (error, { longitude, latitude, place } = {}) => {
    if (error) {
      return res.send({ error });
    }
    getWeather(latitude, longitude, (error, { temperature, humidity }) => {
      if (error) {
        return res.send({ error });
      }
      return res.send({ temperature, humidity, place });
    });
  });
});

app.listen(3001, () => {
  console.log('服务器运行在端口3001');
});

验证步骤:

  1. 确保后端服务器运行在3001端口,并且已经安装并启用了cors中间件。
  2. 前端修改后发送请求,现在应该能正确拿到后端返回的错误信息或者天气数据了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 13:52:29