Uncaught (in promise) TypeError: Failed to fetch at getCount



我需要一个帮助与一个fetch问题,我所面临的。

我确实创建了一个JS函数来读取国家。我确实插入了我的wampserver "www/data_api/country.json"。服务器是在线的,当使用链接(http://localhost/data_api/country)直接访问它时工作正常。

问题是当我调用这个链接在我的异步函数。在我的代码下面:

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)

我希望在console.log中看到所有国家的对象。

试试这段代码,看看控制台记录的错误。

import React, { useState, useEffect } from 'react'
export default function Country() {
const [country, setCountry] = useState([]);
useEffect( ()=>{
const getCountry = async ()=>{
try{
const res = await fetch("http://localhost/data_api/country.json");
const getcon = await res.json();
console.log(getcon);
setCountry(  getcon);
}catch(error){
console.log('An error occured')
console.log(error)
}
}
getCountry();
},[]);
return (
<div>Country</div>
)
}

相关内容

  • 没有找到相关文章

最新更新