我是Reactjs的新手,并且正在使用create-react-app入门,但是我不明白如何进行api调用来获取数据。这是我的代码:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
// import { URL, KEY, city, countryCode } from './config.json';
const KEY = "d7ba7d7818dd3cec9ace78f9ad55722e";
const URL = "api.openweathermap.org/data/2.5";
const CITY = "Paris";
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentDidMount() {
var url = `${URL}/weather?q=${CITY}&APPID=${KEY}&units=metric`;
console.log(url);
fetch(url).then(
response => response.json()
).then(
json => {
console.log(json);
this.setState({data: json});
}
);
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;
render方法只是create-react-app中的默认渲染,我没有更改它。我只添加了构造函数和componentDidMount方法。 我尝试从OpenWeatherMap API中获取一些数据,将其添加到状态并记录到控制台。
该请求在邮递员中完美运行,但在我的应用中引发了以下错误:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
有人可以帮助我吗?
答案 0 :(得分:4)
在URL中包含协议以解决问题。提取请求的响应未成功,因此当您尝试将响应解析为JSON时,它会引发异常,因为响应无效的JSON。
const KEY = "d7ba7d7818dd3cec9ace78f9ad55722e";
// Made change here
const URL = "https://api.openweathermap.org/data/2.5";
const CITY = "Paris";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: {}
};
}
componentDidMount() {
var url = `${URL}/weather?q=${CITY}&APPID=${KEY}&units=metric`;
console.log(url);
fetch(url).then(
response => response.json()
).then(
json => {
console.log(json);
this.setState({data: json});
}
);
}
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('example'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="example"></div>