【问题标题】:Can't get json from unsplash api无法从 unsplash api 获取 json
【发布时间】:2018-07-16 13:28:09
【问题描述】:

我试图用 unsplash api 制作一个图像搜索应用程序。我可以通过像this 这样将 url 写入浏览器来访问 api,但我无法让它在我的代码中工作。有人可以帮忙吗?也没有发生错误,我正在尝试将 json 文件打印到控制台。我正在关注此文档here

import React, { Component } from 'react';
import './App.css';


class App extends Component {
  constructor(props) {
    super(props);

      this.state = {
        applicationId: '1424074b20f17701ec8c0601fd15ca686c70e2cb0e645f8137533d8063e664bc',
        url: 'https://api.unsplash.com/search/photos?client_id=',
        pagecount: 1
      }

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    let query = document.getElementById('input').value;
    fetch(this.state.url + this.state.applicationId + '&query=' + query + '&page=' + this.state.pagecount)
      .then(json => {
        console.log(json)
      })
      .catch(err => console.log('error occured' + err));
  }

  render() {
    return (
      <div className="App">
        <form id='form'>
          <input type='text' id='input' ></input>
          <input type='submit' id='submit' onClick={this.handleClick} ></input>
        </form>
        <div id='field' >
        </div>
      </div>
    );
  }
}

export default App;

【问题讨论】:

    标签: javascript html reactjs create-react-app


    【解决方案1】:

    问题:You Fetch 不返回实际的 JSON,它只返回 HTTP 响应。为了从响应中提取 JSON 正文内容,我们使用 json() 方法。

    你检查过你的最终URL吗?我只做了很少的改动就得到了结果。你得到client_id和查询词了吗?

    解决方案

    const client_id ="1424074b20f17701ec8c0601fd15ca686c70e2cb0e645f8137533d8063e664bc"
    const query = 'woods';
    function makeCall(){
    
      fetch(`https://api.unsplash.com/search/photos?client_id=${client_id}&query=${query}`,{method:'get'}).
    then(res=>res.json())
    .then(res=>console.log("boommer",res))
    .catch(res=>console.log("error",res))
    
    }
    makeCall();

    react CodeSandBox的工作示例

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 2012-04-26
      • 1970-01-01
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多