create react app项目中fetch请求本地json数据报错

在create react app项目中,使用fetch请求本地json数据时可能会遇到报错。错误原因是json文件未被正确处理和打包。解决方案包括将json文件放在public目录下,或利用process.env.PUBLIC_URL引用。这样做是因为在src或node_modules中的文件不会被自动包含在webpack构建的前端包中,因此需要显式处理。
摘要由CSDN通过智能技术生成

fetch请求本地json数据报错

export const getInitToDoLists = (localUrl) => {
    fetch(localUrl)
        .then(res => res.json())
        .then(data => {
            console.log('local data', data)
        })
}

错误提示信息如下:
在这里插入图片描述

解决方案:
将对饮的json数据置于public目录下,使用fetch时再传入相对于public的文件url即可;或者使用process.env.PUBLIC_URL+’/finename.json’(来源于create react app文档using the public folder)

原因推测:
If you need to use a file from src or node_modules, you’ll have to copy it there to explicitly specify your intention to make this file a part of th

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值