【问题标题】:Error on authentication React JS认证 React JS 时出错
【发布时间】:2018-07-16 08:38:21
【问题描述】:

我正在尝试使用 unsplash api 实现搜索功能以从 unsplash.com 搜索图像。但由于某种原因,我无法正确进行身份验证。我收到网络错误。

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。我从未体验过身份验证。

【问题讨论】:

  • 能否显示错误(屏幕或代码)?
  • ./src/App.js 第 25 行:意外使用 'location' no-restricted-globals 搜索关键字以了解有关每个错误的更多信息。
  • 我不知道你为什么需要在你的情况下使用location。您可以评论/删除该行并显示您之后得到的错误吗? (最好通过编辑您的问题,以便其他人可以轻松查看)
  • 这似乎是一个 lint 错误,但不是 NetworkError
  • 如果我将位置注释掉,则不会出错,但是当我尝试搜索时,它会出现网络错误。关于被阻止的“跨源”请求

标签: javascript reactjs create-react-app


【解决方案1】:

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

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

【讨论】:

  • 哦,但是我在哪里使用该查询字符串?当我运行应用程序时,我被重定向到身份验证代码,然后我只看到错误
猜你喜欢
  • 1970-01-01
  • 2019-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-09
  • 1970-01-01
  • 1970-01-01
  • 2018-06-19
相关资源
最近更新 更多