Fetch api data with create-react-app(使用 create-react-app 获取 api 数据)
问题描述
我是 reactjs 新手,我正在使用 create-react-app 开始,但我不明白如何进行 api 调用来获取数据.这是我的代码:
I'm new to reactjs, and I'm using create-react-app to get started, but I can't understand how make an api call to fetch data. Here is my code:
render 方法只是 create-react-app 的默认渲染,我没有更改它.我只添加了构造函数和 componentDidMount 方法.我尝试从 OpenWeatherMap API 获取一些数据,将其添加到状态并将其记录到控制台.
The render method is just the default render from create-react-app, I didn't change it. I only added the constructor and componentDidMount methods. I try to fetch some data from the OpenWeatherMap API, add it to the state and log it to the console.
该请求在邮递员中完美运行,但在我的应用程序中引发了此错误:SyntaxError:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符
The request works perfectly in postman, but raises this Error in my app:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
谁能帮帮我?
推荐答案
在 URL 中包含协议以解决问题.获取请求的响应不成功,因此当您尝试将响应解析为 JSON 时,它会抛出异常,因为响应它不是有效的 JSON.
Include protocol with URL to resolve the problem. Response of fetch request is not success so when you try to parse response as JSON it throws exception because response it not valid JSON.
这篇关于使用 create-react-app 获取 api 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!