Skip to content

Instantly share code, notes, and snippets.

@reidstidolph
Created October 11, 2019 03:10
Show Gist options
  • Save reidstidolph/1f90caa1cef50b931409262fd7d372c6 to your computer and use it in GitHub Desktop.
Save reidstidolph/1f90caa1cef50b931409262fd7d372c6 to your computer and use it in GitHub Desktop.
Promise-based sample fetching a JWT from the 128T REST API.
/*******************************************************************************
* *
* Promise-based sample fetching a JWT from the 128T REST API. *
* *
*******************************************************************************/
const https = require('https')
const host128t = 'my.128t.host.com' // Address or FQDN of 128T host
const apiUser = 'admin' // Authorized API user
const apiSecret = 'mySup3rS3cr3t' // API user secret
// REST body to contain JSON object containing API username and password
const reqBody = JSON.stringify({'username':apiUser,'password':apiSecret})
// set up HTTP(S) request options
let reqOptions = {
host : host128t,
path : '/api/v1/login',
method : 'POST',
headers : {
'content-type' : 'application/json',
'content-length' : Buffer.byteLength(reqBody, 'utf8')
},
rejectUnauthorized : false
}
// Promise returning function to get JWT
const getToken = function() {
return new Promise((resolve, reject) => {
const request = https.request(reqOptions, (response) => {
// handle http errors
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error('Failed to load page, status code: ' + response.statusCode))
}
const body = []
response.on('data', (chunk) => body.push(chunk))
response.on('end', () => resolve(body.join('')))
})
// handle connection errors
request.on('error', (err) => reject(err))
// write JSON to request
request.write(reqBody)
request.end()
})
}
// Begin getting token
getToken()
.then((data) => {
// handle results
process.stdout.write(`API returned: ${data}\n`)
process.exit(0)
})
.catch((err) => {
// handle error
process.stderr.write(`API request failed: ${err}\n`)
process.exit(1)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment