我正在尝试使用节点http
本机库读取请求的内容
我想发出一个 POST 请求,我已经成功地做到了,但是然后使用保存的响应块使用我的 lambda 函数上的回调将它们作为整体输出。
这是我的代码:
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);
}
我可以在哪里放置回调以输出dataStr
变量内容作为此端点的响应?
感谢您的洞察力。