Axios从API获取数据-React.js

埃泽韦多

我正在使用axios从API获取数据,我试图做一些非常简单的事情,而我之前已经做过。我可以在控制台上看到已发出请求,但无法输出数据或console.log()消息。

componentDidMount() {
    axios.get("https://dog-api.kinduff.com/api/facts")
    .then( response => {
        console.log("Facts: ")
        this.setState({DogFact:response.data})
    })
    .catch( err => {
        this.setState({error:err.data.message})
    })
}

api的响应是带有数组的对象。

{facts["fact written here"]}

它应该非常简单,但是如果我尝试这样做:

axios.get("https://dog-api.kinduff.com/api/facts")
.then( response => {
    console.log("Facts: ", response) //This wont show up on the console
    this.setState({DogFact:response.facts[0]}) //This wont work.
})

我真的不明白什么可能是错的。有人可以帮我吗?

哈姆扎·穆拉(Hamzah Murrar)

在package.json中添加此行

"proxy": "https://dog-api.kinduff.com/api/"

然后在您的axios调用中将其更改为:

axios.get("/facts")
.then( response => {
    console.log("Facts: ", response) 
    this.setState({DogFact:response.facts[0]})
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用React.js获取数据属性

React.js渲染JSON响应,共同获取或axios

React JS使用Axios在XMLHttpRequest中获取错误

在与axios的react-native中使用POST方法获取API数据

React.js获取Giphy API

如何在redux动作中从axios调用获取数据?React JS搜索项目

从React中的Axios返回获取的数据

从react.js从Express.js API获取数据。邮递员的要求有效

React useEffect无限循环获取数据axios

React / Axios:使用Coinmarketcap的密钥获取API数据

REACT JS如何显示从onClick获取的API数据?

从Firebase获取数据(React,Axios)

React中的Chart JS不获取数据

想要从React Js中的API获取数组中的数据

在react.js上使用Axios从API中提取数据。我究竟做错了什么?

React.js如何显示我从API获取的数组数据?

如何使用 React.js 获取 API

React JS 动态数据获取

在 React JS 中使用 Fetch 获取 API 数据

在 React.js 中获取 API 获取数据后加载组件

React js 从带有 React 钩子的分页 api 中获取所有数据

React/Axios - 从 API 获取损坏的图像

从 api 获取 json 响应 - react.js

使用 axios 获取请求的结果填充对象(在 React js 中)

如何从 JSON API 中的数组对象获取数据?(React.js)

在 firebase 上部署 React App 后,Axios 无法获取 API 数据

使用 React js 从 AWS 的端点获取数据

React 和 Express:使用 Axios 从 3rd 方 API 获取数据

react js:使用获取请求条件的 axios fecth 数据:我想要具有这些值的名称:true