0

I have an azure function with this line of code.

var myReq = https.request(options, function(res) {
            context.log('STATUS: ' + res.statusCode);
            context.log('HEADERS: ' + JSON.stringify(res.headers));
            body += res.statusCode
            res.on('data', function (chunk) {
                context.log('BODY: ' + chunk);
            });
        });

        myReq.on('error', function(e) {
            context.log('problem with request: ' + e.message);
        });

        myReq.write(postData);
        myReq.end();

But my code seems to just skip this part of code, with no errors. I am new to Azure and node.js so I might have missed some basic parts in setting this up.

Any ideas?

Edit: Here is my full code

const https = require('https');
const querystring = require('querystring');

module.exports = async function (context, req) {

    if (req.query.accessCode || (req.body && req.body.accessCode)) {
        context.log('JavaScript HTTP trigger function processed a request.');
        var options = {
            host: 'httpbin.org',
            port: 80,
            path: '/post',
            method: 'POST'
        };

        var postData = querystring.stringify({
            client_id : '1234',
            client_secret: 'xyz',
            code: req.query.accessCode
        });

        var body = "";
        var myReq = https.request(options, function(res) {
            context.log('STATUS: ' + res.statusCode);
            context.log('HEADERS: ' + JSON.stringify(res.headers));
            body += res.statusCode
            res.on('data', function (chunk) {
                context.log('BODY: ' + chunk);
            });
        });

        myReq.on('error', function(e) {
            context.log('problem with request: ' + e.message);
        });

        myReq.write(postData);
        myReq.end();
        context.log("help");
        context.res = {
            status: 200,
            body: "Hello " + (body)
        };
    } else {
       context.res = {
            status: 400,
           body: "Please pass a name on the query string or in the request body"
      };
    }
};
mionnaise
  • 188
  • 1
  • 18

2 Answers2

0

Ideally it should work. You can also try using request module like below

const request = require('request');
request('http://www.google.com', function (error, response, body) {
  console.error('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

Try and see if it helps.

Mohit Verma
  • 5,140
  • 2
  • 12
  • 27
0

Solved by doing await properly. Used this as guide.

var https = require('https');
var util = require('util');
const querystring = require('querystring');
var request = require('request')

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    /*if (req.query.name || (req.body && req.body.name)) {*/
    var getOptions = {
        contentType: 'application/json',
        headers: {
            'Authorization': <bearer_token>
         },
    };
    var postData = {
        "key": "value"
    };
    var postOptions = {
        method: 'post',
        body: postData,
        json: true,
        url: <post_url>,
        headers: {
            'Authorization': <bearer_token>
         },
    };
    try{
        var httpPost = await HttpPostFunction(context, postOptions);
        var httpGet = await HttpGetFunction(context, <get_url>, getOptions);
        return {
            res: httpPost
        };
    }catch(err){
       //handle errr
       console.log(err);
    };
};

async function HttpPostFunction(context, options) {
    context.log("Starting HTTP Post Call");
    return new Promise((resolve, reject) => {
        var data = '';
        request(options, function (err, res, body) {
            if (err) {
              console.error('error posting json: ', err)
              reject(err)
            }
            var headers = res.headers;
            var statusCode = res.statusCode;
            //context.log('headers: ', headers);
            //context.log('statusCode: ', statusCode);
            //context.log('body: ', body);
            resolve(body);
          })
    });
};

async function HttpGetFunction(context, url, options) {
    context.log("Starting HTTP Get Call");
    return new Promise((resolve, reject) => {
        var data = '';
        https.get(url, options, (resp) => {
            // A chunk of data has been recieved.
            resp.on('data', (chunk) => {
                data += chunk;
            })
            // The whole response has been received. Print out the result.
            resp.on('end', () => {
                resolve(JSON.parse(data));
            });
        }).on("error", (err) => {
            console.log("Error: " + err.message);
            reject(err.message);
        });
    });
};
mionnaise
  • 188
  • 1
  • 18