Making HTTPS Request with Node.js and get JSON result

Making HTTPS requests is very important for the application. I never work with NodeJS before this experience with Alexa: call an API on Azure from Alexa Developer Console with nodejs editor on the portal and get the JSON result. In this post, you can read how to perform a GET Request with my ‘function httpGet’ (async/await) ⬇️

Node.js Design Patterns: Design and implement production-grade Node.js applications using proven patterns and techniques

https.request

1
var https = require('https');

function httpGet

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function httpGet(typeOfFilter) {
    
  return new Promise(((resolve, reject) => {
    var options = {
        host: '00000000000000000000000000000000.azurewebsites.net',
        port: 443,
        path: '/api/BlaBlaBla?type=' + typeOfFilter ,
        method: 'GET'
    };
    

    const request = https.request(options, (response) => {
        
      response.setEncoding('utf8');
      let returnData = '';

      response.on('data', (chunk) => {
        returnData += chunk;
      });

      response.on('end', () => {
            resolve(JSON.parse(returnData));
      });

      response.on('error', (error) => {
          throw error;
      });
    });
    
    request.end();
  }));
  
}

https.request - get result

1
2
3
response.on('data', (chunk) => {
    returnData += chunk;
});

https.request - parse json and return

1
2
3
response.on('end', () => {
    resolve(JSON.parse(returnData));
});

function httpGet: how to call?

1
2
3
4
5
6
7
[...]
async handle(handlerInput) {
  
        const response = await httpGet('01');
        
},
[...]