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

React JS中Fetch请求失败求助:调用指定接口返回Failed to fetch

Fetch请求失败排查方案

调用指定接口时出现Uncaught (in promise) TypeError: Failed to fetch错误,相关代码及翻译后的错误信息如下:

代码

import "./styles.css";
import { useEffect } from 'react'
export default function App() {
  useEffect(()=>{
    fetch('https://serverbackend-br77.onrender.com/posts/6425abddd6e26eee1f7b5508')
      .then((res)=> res.json())
      .then((respuesta) => console.log(respuesta))
  })
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

错误信息(翻译后)

未捕获(在Promise中)类型错误:Fetch请求失败
    在 eval (App.js:5:5)
    在 commitHookEffectListMount (react-dom.development.js:23150:26)
    在 invokePassiveEffectMountInDEV (react-dom.development.js:25154:13)
    在 invokeEffectsInDev (react-dom.development.js:27351:11)
    在 commitDoubleInvokeEffectsInDEV (react-dom.development.js:27330:7)
    在 flushPassiveEffectsImpl (react-dom.development.js:27056:5)
    在 flushPassiveEffects (react-dom.development.js:26984:14)
    在 commitRootImpl (react-dom.development.js:26935:5)
    在 commitRoot (react-dom.development.js:26682:5)
    在 performSyncWorkOnRoot (react-dom.development.js:26117:3)
    在 flushSyncCallbacks (react-dom.development.js:12042:22)
    在 flushSync (react-dom.development.js:26201:7)
    在 Object.scheduleRoot (react-dom.development.js:27810:5)
    在 eval (react-refresh-runtime.development.js:280:17)
    在 Set.forEach (<anonymous>)
    在 Object.performReactRefresh (react-refresh-runtime.development.js:259:25)
    在 eval (refresh-helper.js:13:20)

排查及解决步骤

  1. 先捕获具体错误详情
    原代码没处理Promise的失败状态,看不到真实错误原因。修改代码添加catch:

    useEffect(()=>{
      fetch('https://serverbackend-br77.onrender.com/posts/6425abddd6e26eee1f7b5508')
        .then((res)=> res.json())
        .then((respuesta) => console.log(respuesta))
        .catch(err => console.error('请求错误详情:', err)) // 新增捕获错误
    }, []) // 加空依赖数组,避免组件重复渲染时多次发起请求
    
  2. 检查接口可用性
    直接在浏览器地址栏访问请求的URL:

    • 如果返回404,说明该ID的资源不存在,检查资源ID或接口路径是否正确;
    • 如果无法打开页面,大概率是Render上的免费服务休眠了(长时间未访问会自动休眠),等待几分钟后重新请求唤醒服务即可。
  3. 排查CORS跨域问题
    浏览器会拦截跨域请求,若后端没配置CORS就会触发这类错误:

    • 后端需配置CORS规则,允许前端所在域名(比如CodeSandbox的域名)访问;
    • 本地调试可临时用浏览器插件关闭CORS验证(仅用于调试,生产环境不建议)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 05:23:09