Javascript 如何授权访问api?反应JS
我正在尝试制作一个单页web应用程序,用户可以从Unsplash.com搜索照片。我正在使用unsplash api,无法确定如何通过授权。我没有授权方面的经验Javascript 如何授权访问api?反应JS,javascript,reactjs,create-react-app,Javascript,Reactjs,Create React App,我正在尝试制作一个单页web应用程序,用户可以从Unsplash.com搜索照片。我正在使用unsplash api,无法确定如何通过授权。我没有授权方面的经验 import React, { Component } from 'react'; import Unsplash, { toJson } from 'unsplash-js'; import './App.css'; const unsplash = new Unsplash({ applicationId: aplicatio
import React, { Component } from 'react';
import Unsplash, { toJson } from 'unsplash-js';
import './App.css';
const unsplash = new Unsplash({
applicationId: aplicationId,
secret: secret,
callbackUrl: callbackUrl,
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;
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;
import React,{Component}来自'React';
从“Unsplash js”导入Unsplash,{toJson};
导入“/App.css”;
const unsplash=新的unsplash({
applicationId:aplicationId,
秘密:秘密,
callbackUrl:callbackUrl,
标题:{
“接受版本”:“v1”
}
});
类应用程序扩展组件{
建造师(道具){
超级(道具);
this.handleClick=this.handleClick.bind(this);
}
componentDidMount(){
const authenticationUrl=unsplash.auth.getAuthenticationUrl([
“公众”,
“读取用户”,
“写入用户”,
“阅读照片”,
“写照片”
]);
分配(authenticationUrl);
unsplash.auth.userAuthentication(query.code)
.然后(toJson)
。然后(json=>{
//log(unsplash.auth.userAuthentication(query.code))
unsplash.auth.setBearerToken(json.access\u令牌);
})
.catch(err=>console.log('Auth err',err));
}
handleClick(){
让query=document.getElementById('input').value;
unsplash.search.photos(query,1)//api提供的函数
.然后(toJson)
。然后(json=>{
log(json);
});
}
render(){
返回(
);
}
}
导出默认应用程序;
我还按照这些api说明做了所有事情api似乎需要OAuth身份验证。你需要一台自己的服务器。好啊但我可以看到,在不进行身份验证的情况下,您可以使用API执行一些操作。但是当我删除
组件willmount()
并尝试搜索一个图像时,它说CORS请求搜索照片失败,我认为您应该使用unsplash.search.photos(“dogs”,1)。然后(toJson)。然后(json=>{//Your code})。在代码中,您获得了令牌授权,但它位于unsplash对象中。通常在调用API时,您必须在Url头中设置BearToken,以便服务器能够识别,您的获取只需在头中没有标记的情况下正常调用即可。是的,你现在可以看到我编辑了onClick函数,但是现在它告诉我查询没有定义,位置是意外的/src/App.js第29行:“位置”的意外使用没有限制的全局变量第30行:“查询”没有定义没有未定义的,而且在显示这些错误后,它会将我指向身份验证代码。如何让代码转到query.code?componentDidMount中缺少“query”局部变量