Example: Node.js Device API

Sample code to consume the Device API using Node.js.


var https = require('https');
var moment = require('moment');
var CryptoJS = require("crypto-js");
const apiPath = '/api/device';
const timestamp = moment().utc().format('YYYY-MM-DD HH:mm:ss');
console.log(timestamp);
const SECRET = "INSERT_SECRET";
const API_KEY = "INSERT_API_KEY";
const secretMessage = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA256('GET' + timestamp + apiPath, SECRET));
const options = {
    "method": "GET",
    "hostname": "www.kbremote.net",
    "port": 443,
    "path": apiPath,
    "headers": {
        "Authentication": API_KEY + ':' + secretMessage,
        "Timestamp": timestamp
    },
    "Content-Type": "application/json"
};
const req = https.request(options, function (res) {
    console.log('Status: ' + res.statusCode);
    res.on('data', function (chunk) {
        console.log('Response: ' + chunk);
    });
    res.on('end', function () {
        console.log('end of request');
    });
});
req.on('error', error => {
    console.log(error)
});
req.end();


If you need to include JSON in the body you can do the following:


//JSON
const post_data = '{\"DeviceGroupID\":2}';
//ADDED CONTENT-LENGTH
const options = {
    "method": "PATCH",
    "hostname": "www.kbremote.net",
    "port": 443,
    "path": apiPath,
    "headers": {
        "Authentication": API_KEY + ':' + secretMessage,
        "Timestamp": timestamp,
        "Content-Type": "application/json",
        "Content-Length": post_data.length
    }
//ADDED REQ.WRITE
const req = https.request(options, function (res) {
    console.log('Status: ' + res.statusCode);
    res.on('data', function (chunk) {
        console.log('Response: ' + chunk);
    });
    res.on('end', function () {
        console.log('end of request');
    });
});
req.write(post_data);
req.on('error', error => {
    console.log(error)
});
req.end();

This article was helpful for 1 person. Is this article helpful for you?