我正在尝试使用twitter的rest api。目前我想使用搜索API。为此,我只需要application only authentication
。我正在使用reactjs前端。我正在使用html中的react库。以下是创建组合密钥+密钥的代码。我不知道如何转换为base64。
var key = "*****************";
var secret = "******************";
var cat = key +":"+secret;
var credentials = ?? How to convert cat to base64 ??
这是完整的代码。让我知道我必须包括哪些库。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Twitter API</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class Module extends React.Component {
constructor(props) {
super(props);
var key = "*****************";
var secret = "******************";
var cat = key +":"+secret;
var credentials = cat
this.state = {
bearer_token:"XXXXXXXXXXX"
}
this.handleClickGettoken = this.handleClickGettoken.bind(this)
}
handleClickGettoken(){
var url = 'https://api.twitter.com/oauth2/token';
axios({ url: url,
method:'POST',
headers: {
"Authorization": "Basic " + this.credentials,
"Content-Type":"application/x-www-form-urlencoded;charset=UTF-8"
},
body: "grant_type=client_credentials"
})
.then(function(response) {
this.setState(prevState => ({
bearer_token: response
})
)
});
}
render() {
return (
<div>
<p>{ this.state.bearer_token }</p>
<button onClick={this.handleClickGettoken}>GetBearerToken</button>
</div>
);
}
}
ReactDOM.render(
<Module />,
document.getElementById('root')
);
</script>
</body>
</html>
答案 0 :(得分:0)
这应该这样做。
var credentials = new Buffer(cat).toString('base64');
如果&#39;缓冲区&#39;不可用,请尝试:
var credentials = window.btoa(cat);