javascript - 认证 React JS 时出错
问题描述
我正在尝试使用 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 。我从未有过身份验证的经验。
解决方案
Unsplash 的文档建议将参数传递query.code
给unsplash.auth.userAuthentication
,我相信他们打算让您解析查询字符串并声明query
first 的值。
您可以使用诸如查询字符串之类的库来帮助您实现这一目标。
推荐阅读
- regex - 正则表达式 - 提取字符串
- java - 如何更改继承类中的集合类型?
- tinymce - 从 tinymce 向页面添加内容
- ios - UIProgressView 没有在 Swift3 iOS 中的 UICollectionView 内更新
- android - 为什么片段类应该是公开的?
- python - 在 Python 中使用字符串调用内置函数
- python - 对某事的编码仅发生在某些编码中?
- python - 使用自定义距离指标保存 sklearn 模型
- javascript - 当我们勾选复选框时,如何添加表格字段值并将其显示在输入中?
- aframe - gltf 材质覆盖停止动画混合器