Where should I put callback to return data after node https.request call?

355 views Asked by At

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.

1

There are 1 answers

2
siraj pathan On

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