首页 > 解决方案 > 获取 http.get Node.js 的前两个字节

问题描述

我需要 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...
};

有任何想法吗?多谢!!

标签: node.jsamazon-web-serviceshttpsaws-lambda

解决方案


问题是您调用的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
});

推荐阅读