简体   繁体   English

无法从Unsplash API获取JSON

[英]Can't get json from unsplash api

I was trying to make a image search app with unsplash api. 我试图使用unsplash api制作图像搜索应用。 I can access api by writing the url in to the browser like this this but I can't get it to work within my code. 我可以通过像这样的浏览器编写的URL访问API 这个 ,但我不能得到它我的代码中工作。 anyone can help? 有人可以帮忙吗? Also no error is occurring and I am trying to get the json file to be printed to the console. 另外也没有错误发生,我正在尝试将json文件打印到控制台。 I am following this documentation 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;

Problem : You Fetch does not return actual JSON, it return just HTTP response. 问题 :您获取未返回实际的JSON,它仅返回HTTP响应。 To extract the JSON body content from the response, we use the json() method. 要从响应中提取JSON正文内容,我们使用json()方法。

Have you checked your final URL ? 您检查了最终URL吗? I got a result just with few changes. 我得到的结果只有很少的变化。 Are you getting client_id and query word? 您是否获得client_id和查询词?

Solution

 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(); 

Working example of react CodeSandBox React CodeSandBox的工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM