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

React中fetch请求本地JSON遇Uncaught (in promise) TypeError问题求助

React Fetch请求本地WAMP静态文件报错解决方案

问题概述

  • WAMP服务器www/data_api目录下存放country.json文件,直接访问http://localhost/data_api/country.json(或用户所述http://localhost/data_api/country)可正常获取内容
  • React组件中通过async函数调用该URL时,抛出Uncaught (in promise) TypeError: Failed to fetch错误

代码示例

import React, { useState, useEffect } from 'react'

function Country() {
    const [country, setCountry] = useState([]);

    useEffect( ()=>{
        const getCountry = async ()=>{
            const res = await fetch("http://localhost/data_api/country.json");
            const getcon = await res.json();
            console.log(getcon);
            setCountry(await getcon);
        }
        getCountry();
    },[]);

  return (
    <div>Country</div>
  )
}

export default Country

错误信息

Uncaught (in promise) TypeError: Failed to fetch
    at getCountry (Country.js:8:1)
    at Country.js:13:1
    at commitHookEffectListMount (react-dom.development.js:23150:1)
    at commitPassiveMountOnFiber (react-dom.development.js:24926:1)
    at commitPassiveMountEffects_complete (react-dom.development.js:24891:1)
    at commitPassiveMountEffects_begin (react-dom.development.js:24878:1)
    at commitPassiveMountEffects (react-dom.development.js:24866:1)
    at flushPassiveEffectsImpl (react-dom.development.js:27039:1)
    at flushPassiveEffects (react-dom.development.js:26984:1)
    at commitRootImpl (react-dom.development.js:26935:1)

解决方案

1. 解决跨域问题

React开发服务器默认运行在3000端口,WAMP的Apache默认在80端口,属于跨域请求,这是最常见的原因:

  • 方案一:配置React代理
    在React项目根目录的package.json中添加代理配置:

    "proxy": "http://localhost"
    

    修改fetch路径为相对路径:

    const res = await fetch("/data_api/country.json");
    

    重启React开发服务器后,请求会自动转发到WAMP服务器。

  • 方案二:配置Apache CORS
    打开WAMP的Apache配置文件(httpd.conf或httpd-vhosts.conf),添加CORS允许规则:

    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
    Header set Access-Control-Allow-Headers "Content-Type"
    

    保存后重启Apache服务。

2. 校验请求路径一致性

确认fetch的URL与直接访问的地址完全匹配:

  • 如果直接访问的是http://localhost/data_api/country(无.json后缀),则代码中的fetch路径需改为该地址
  • 检查文件实际名称是否与请求路径一致,避免拼写错误

3. 优化代码并添加错误捕获

  • 移除setCountry(await getcon)中的多余await,getcon已经是解析后的JSON对象
  • 添加try-catch块捕获具体错误,便于排查:
    const getCountry = async ()=>{
        try {
            const res = await fetch("http://localhost/data_api/country.json");
            // 检查响应状态是否正常
            if (!res.ok) throw new Error(`请求失败,状态码:${res.status}`);
            const getcon = await res.json();
            console.log(getcon);
            setCountry(getcon);
        } catch (err) {
            console.error('请求异常:', err);
        }
    }
    

4. 检查端口占用情况

确保WAMP的Apache服务(默认80端口)和React开发服务器(默认3000端口)未被其他程序占用,可通过任务管理器或端口检测工具排查。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:41:17