编程语言
首页 > 编程语言> > javascript – 使用create-react-app获取api数据

javascript – 使用create-react-app获取api数据

作者:互联网

我是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:JSON数据的第1行第1列的意外字符

谁能帮我 ?

解决方法:

包含带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>

标签:create-react-app,javascript,reactjs,fetch
来源: https://codeday.me/bug/20190910/1801747.html