Http requests for json

Hi,

hoping someone a bit more knowledgeable might be able to offer some suggestions on what I might be doing wrong in the Homey app I’m writing. Basically I’m trying to get some json data from a Solar Battery inverter via its API, however I instead seem to be receiving some html data instead. My code is as follows (except with and having the correct values):

'use strict';

var http = require('http');

const Homey = require('homey');

var options = {
  host: 'api.givenergy.cloud',
  path: '/v1/inverter/<SERIAL NUMBER>/system-data/latest/',
  method: 'GET',
  headers: {'Authorization': 'Bearer <API KEY>',
  'Content-Type': 'application/json',
  'Accept': 'application/json'}
};

class GivEnergy extends Homey.App {

  callback = function(response) {
    console.log('Callback');
    var str = '';
    response.on('data', function (chunk) {
      str += chunk;
    });

    response.on('end', function() { 
      console.log(str);
    });

    //var jsonObject = JSON.parse(str);
  }

  async onInit() {
    this.log('GivEnergy has been initialized');

    var req = http.request(options, this.callback);
    req.end();

    this.log('End');
  }
}
module.exports = GivEnergy;

It is based on this Powershell script (which returns the correct data):

$headers_Giv_En = @{
 'Authorization'="Bearer $GivEnergyPortalAPI"
 'Content-Type'='application/json'
 'Accept'='application/json'
 }
$Giv_En =  Invoke-RestMethod -Method 'Get' -Uri https://api.givenergy.cloud/v1/inverter/$SerialNum/system-data/latest/ -Headers $headers_Giv_En
$Giv_En | ConvertTo-Json -Depth 10 | Out-File -FilePath .\InvData_Now.txt -Encoding ASCII

Write-Output "Data Saved to: InvData_Now.txt"
Write-Output "All done - Exit in 5...." 
start-sleep -s 5

Exit

I suspect maybe it is something to do with the header data, but that looks correct to me. Does anyone have any suggestions? I’m fairly new to Javascript.

1 Like

Could give us an example to what outputs both code snipping gives?
Maybe the cloud doesn’t accept http. use require(‘https’) instead

Also check the status code of the response. response.statusCode
200, 201 is ok, everything else is usually bad.

Thanks, you were right, the issue was the use of http rather than https. So it was returning a status code of 301 indicating a redirect to the https version and the data returned was html redirection code.