在AWS lambda函数中,我需要http.get的前两个字节(用于魔术验证)。 这是我的代码:
exports.handler = (event, context, callback) => {
var https = require('https');
var url= "https://mail.google.com/mail/u/0/?ui=2&ik=806f533220&attid=0.1&permmsgid=msg-a:r-8750932957918989452&th=168b03149469bc1f&view=att&disp=safe&realattid=f_jro0gbqh0";
var result= https.get(url , (resp) => {
let data = '';
// 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', () => {
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
callback(null, '3');// I want to return the first two bytes...
};
有什么想法吗? 非常感谢!
答案 0 :(得分:0)
问题是您调用callback
的时间过早,即在您收到resp
的回叫之前。尝试移动回调,例如
resp.on('data', (chunk) => {
data += chunk;
var data = // here you may have the data you need, either call the callback temporarily or execute the callback immediately
callback(null, data);
});
或等待resp
结束:
resp.on('end', () => {
// pass the temporarily stored data to the callback
callback(null, data);
});
或者如果resp
导致错误:
resp.on("error", (err) => {
console.log("Error: " + err.message);
callback(err); // make sure to let the caller of Lambda know that the request failed
});