getting twitter bearer token on nodejs(nodejs twitter bearer token 얻기)

in nodejs •  7 years ago  (edited)

From this, https://developer.twitter.com/en/docs/basics/authentication/api-reference/token

요즘 트위터 API 레퍼런스를 읽지않고 npm의 twitter모듈을 쓰다보니 Authentication에 대한 지식이 전혀없었다.
그러다, rate limit 에러에 부딪혀서 제일 먼저 시도해본 방법이 인증방법을 user에서 app-only로 바꾼 것인데,
이때 bearer 토큰을 얻는 기능은 트위터 API console창에서 찾을 수 없었다.

간단히 구글링만 해도 찾을 수 있는 정보지만, 궁금해할 분들이 있을까해서 올립니다.
.
bearer token은 getBearerToken()함수를 따로 실행하여 terminal창에서 보면 됩니다. 'KEY','SECRET'를 자신의 twitter API consumer_key, consumer secret으로 바꿔 주시면 됩니다.

코드



function base64Encode(str){
return new Buffer(str).toString('base64')
}

function getBearerCredentials(key,secret){
return base64Encode(key + ':' + secret);
}

function getBearerToken(){
var credentials = getBearerCredentials('KEY','SECRET');
var options = {
url : 'https://api.twitter.com/oauth2/token',
method : 'POST',
headers: {
'Authorization' : 'Basic ' + credentials,
"Content-Type" : "application/x-www-form-urlencoded;charset=UTF-8"
},
body: 'grant_type=client_credentials'
};

request.post(options, (err, response, body)=>{
if(!err){
var data = JSON.parse(body);
console.log(body);
}
else{
console.log('fail to create bearer token');
}
});
}

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Congratulations @hellioh! You received a personal award!

1 Year on Steemit

Click here to view your Board

Support SteemitBoard's project! Vote for its witness and get one more award!

Congratulations @hellioh! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!