0

I am trying to read the content of a request using node http native library

I want to make a POST request, which I already do successfully, but then use the saved chunks of the response to output them as whole using a callback on my lambda function.

This is my code:

getData: function (event, context, callback) {

    let inputData = event.body;
    let requestData = Object.assign({}, inputData);

    var dataRequest = 'field='+ requestData.Field1;

    var options = {
        method: 'POST',
        hostname: 'my.hostname.com',
        path: '/', 
        headers: {
            "content-type": "application/x-www-form-urlencoded", 
            "connection" : "keep-alive",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",  
        }
    };          

    var dataStr = "";
    var req = https.request(options, function (response) {    
            response.on('data', (chunk) => {dataStr += chunk;}); 
            response.on('end', () => {                   
                console.log(response.statusCode + " " + dataStr);
                //(*) causes "hang up socket error" 
                return callback(dataStr); 
            });            
    });

    req.on('error', err => {          
       return callback("request error:" + err);
    })
    req.write(dataRequest);
    req.end(); //maybe req.end(callback(null,dataStr))?;

    //on commented (*) works fine but dataStr string comes empty
    callback(null,dataStr);
}

Where can I put the callback to output the dataStr variable content as the response of this endpoint?.

Thanks for the insight.

CoderRoller
  • 1,239
  • 3
  • 22
  • 39

1 Answers1

1

For your code, it is right to put callback method inside "end" and "error" callback which is already there. Remove callback from the end of your code.

You can keep callback at any place in your code but if you want to return data then, in that case, it is better to keep inside callback of that function.

One more thing, the callback will not end execution of your code until you return to the main handler

siraj pathan
  • 1,455
  • 1
  • 14
  • 31
  • Hi @siraj, can you write an edited version of my code and show me your change, i think i have tried what you suggested but i get "socket hang up" message from the error callback, when i standalone the http request works fine and i get status 200 ok, is just when i add the callbak to be used as an endpoint which throws the error. – CoderRoller May 18 '18 at 11:45
  • Can you try request library of npm to call API just to debug, because of https library configuration it might not able to call API – siraj pathan May 21 '18 at 06:22