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.