验证React JS时出错

时间:2018-07-16 08:38:22

标签: javascript reactjs create-react-app

我正在尝试实现搜索功能,以使用unsplash api从unsplash.com搜索图像。但是由于某种原因,我无法获得正确的身份验证。我收到了NetworkError。

import React, { Component } from 'react';
import Unsplash, { toJson } from 'unsplash-js';
import './App.css';

const unsplash = new Unsplash({
  applicationId: '',
  secret: '',
  callbackUrl: 'urn:ietf:wg:oauth:2.0:oob',
  headers: {
    "Accept-Version": "v1"
  }
});

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

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

  componentDidMount() {
    const authenticationUrl = unsplash.auth.getAuthenticationUrl([
      "public",
      "read_user",
      "write_user",
      "read_photos",
      "write_photos"
    ]);
    location.assign(authenticationUrl);
    unsplash.auth.userAuthentication(query.code)
      .then(toJson)
      .then(json => {
        //console.log(unsplash.auth.userAuthentication(query.code))
        unsplash.auth.setBearerToken(json.access_token);
      })
      .catch(err => console.log('Auth err', err));

  }

  // handleClick() {
  //   let query = document.getElementById('input').value;
  //   fetch('https://api.unsplash.com/search/photos/?query=' + query)
  //     .then(response => console.log(response))
  //     //.catch(error => console.log('error: ' + error));
  // }

  handleClick() {
    let query = document.getElementById('input').value;
    unsplash.search.photos(query, 1) //function provided by api
      .then(toJson)
      .then(json => {
        console.log(json);
      });
  }

  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;
如果有帮助,

Api文档为https://github.com/unsplash/unsplash-js#authorization。我从没有认证经验。

1 个答案:

答案 0 :(得分:0)

在Unsplash的文档中建议将参数query.code传递给unsplash.auth.userAuthentication的地方,我相信他们打算让您解析查询字符串并首先声明query的值。

您可以使用诸如query-string之类的库来帮助您实现这一目标。