Last active
October 18, 2022 19:20
-
-
Save bytrangle/98a0add2e1c65247df436bfa5c272932 to your computer and use it in GitHub Desktop.
Generate base64-encoded bearer token in Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// import https module for making API calls | |
const https = require('https') | |
// import querystringify to construct a query from an object | |
const qs = require('querystringify') | |
const consumerApiKey = YOUR_CONSUMER_API_KEY | |
const apiSecretKey = YOUR_API_SECRET_KEY | |
const plainCredential = `${consumerApiKey}:${apiSecretKey}` | |
const bearerToken = Buffer.from(plainCredential).toString('base64') | |
// Example API request | |
const options = { | |
hostname: 'api.twitter.com', | |
port: 443, | |
method: 'POST', | |
path: '/oauth2/token?grant_type=client_credentials', | |
headers: { | |
'Authorization': 'Basic ' + bearerToken, | |
}, | |
} | |
const promise = new Promise((resolve, reject) => | |
https.request(options, res => { | |
let data = '' | |
res.on('data', chunk => data += chunk) | |
res.on('end', () => { | |
const auth = JSON.parse(data) | |
if(auth.token_type !== 'bearer') | |
return reject(new Error('Twitter auth failed.')) | |
const accessToken = auth.access_token | |
return resolve(accessToken) | |
}) | |
}).end() | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment