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

React无响应请求问题:Fetch回传数据失败排查

问题分析与修复方案

你的React应用收不到响应,核心原因是后端路由发起CoinAPI请求后,没有把结果返回给客户端——你只在后端打印了日志,但没调用res对象的方法来结束响应并回传数据。我来帮你一步步修复:

1. 核心问题拆解

你的代码里用request库调用了CoinAPI,但完成请求后没有执行res.send()/res.json()这类方法,导致前端的Fetch请求一直处于等待状态,最终超时或无响应。

2. 修复后的代码示例

下面是完善后的路由代码,包含完整的错误处理和数据回传逻辑:

router.get('/', (req, res, next) => { 
  console.log('I got here before request..... >>>>>>>>'); 
  // 修正URL里的双斜杠(//v1 → /v1),避免潜在的请求错误
  request(`https://rest.coinapi.io/v1/exchangerate/BTC?apikey=${API}`, (error, response, body) => { 
    console.log('I got here..... >>>>>>>>'); 
    if(error){ 
      console.log('error >>>>', error);
      // 把错误信息返回给前端,同时设置500状态码表示服务器错误
      return res.status(500).json({ error: error.message });
    }

    // 检查CoinAPI的响应状态是否成功
    if (response.statusCode !== 200) {
      return res.status(response.statusCode).json({ 
        message: 'Failed to fetch data from CoinAPI' 
      });
    }

    try {
      // 将返回的字符串解析为JSON对象,方便前端直接使用
      const exchangeData = JSON.parse(body);
      // 把数据回传给React应用
      res.json(exchangeData);
    } catch (parseError) {
      console.log('JSON parse error >>>>', parseError);
      res.status(500).json({ error: 'Failed to parse response data' });
    }
  }); 
});

3. 额外优化建议

request库已经被官方弃用了,推荐使用更现代的方案,比如Node.js 18+内置的fetch(无需额外安装依赖),代码会更简洁易读:

router.get('/', async (req, res, next) => { 
  console.log('I got here before request..... >>>>>>>>'); 
  try {
    const apiResponse = await fetch(`https://rest.coinapi.io/v1/exchangerate/BTC?apikey=${API}`);
    if (!apiResponse.ok) {
      throw new Error(`CoinAPI returned status: ${apiResponse.status}`);
    }
    const exchangeData = await apiResponse.json();
    res.json(exchangeData);
  } catch (error) {
    console.log('error >>>>', error);
    res.status(500).json({ error: error.message });
  }
});

关键注意点

  • 必须调用res.json()/res.send()来结束响应,否则前端会一直处于等待状态。
  • 完善错误处理逻辑,这样前端能明确知道请求失败的原因,而不是无响应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:32:53