使用create-react-app获取API数据 [英] Fetch api data with create-react-app

查看:103
本文介绍了使用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:

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中获取一些数据,将其添加到状态中并将其记录到控制台中。

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.

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});
      }
    ).catch(error => console.log(error));
  }

  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获取API数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆