2017-08-04 98 views
2

我試圖執行AWS Lambda內部的以下代碼,該代碼僅對ElasticSearch發出POST http請求。NodeJS http post請求讀取超時

我面臨的問題是,似乎nodejs請求有一個讀取超時,並且響應幾乎總是被切斷並引發錯誤。我已檢查該問題與設置爲10秒的AWS Lambda超時無關,並且代碼在不到一秒的時間內拋出錯誤。你可以看到,我試圖把超時設置爲5秒,但我認爲這是連接超時而不是讀超時。

我在做什麼錯?

var http = require('http'); 

exports.handler = (event, context, callback) => { 

var options = { 
    hostname: '172.31.40.10', 
    port: 9200, 
    path: '/articles/es/_search?_source=reference', 
    method: 'POST', 
    headers: { 
     'Content-Type': 'application/json', 
    } 
}; 
var req = http.request(options, function(res) { 
    res.setEncoding('utf8'); 
    res.on('data', function (body) { 
     var parsed = JSON.parse(body); 
     var b = []; 
     for (var i = 0; i < parsed.hits.hits.length; i++) { 
      b.push(parsed.hits.hits[i]._source.reference); 
     } 
     var response = { 
      statusCode: '200', 
      body: JSON.stringify(b), 
      headers: { 
       'Content-Type': 'application/json', 
      } 
     };    
     callback(null, response); 
    }); 
}); 
req.on('error', function(e) { 
    callback(new Error('fallo')); 
}); 
req.setTimeout(5000, function() {req.abort;}) 
req.on('socket', function (socket) { 
    socket.setTimeout(5000); 
    socket.on('timeout', function() { 
     req.abort(); 
    }); 
});  

req.write(MY_QUERY_HERE); 
req.end();  
}; 
+0

什麼是錯誤消息或錯誤代碼你得到? –

回答

1

我認爲你應該在進行任何數據操作之前讓輸入數據流完成。

例子:

var http = require('http'); 
//var _ = require('underscore'); 
function MyPostRequest(callback) { 
var options = { 
    hostname:'172.31.40.10', 
    port:9200, 
    path:'/articles/es/_search?_source=reference', 
    method:'POST', 
    headers:{'Content-Type':'application/json'} 
}; 
http.request(options, function(res) { 
    var tmpstore = ''; //temp. data storage 
    //:Store the continuous incoming data stream 
    res.on('data', function(d){tmpstore += d;}); 
    //:Data reception is done, use it now... 
    res.on('end', function() { 
    var parsed = JSON.parse(tmpstore); var b = []; 
    for (var i = 0; i < parsed.hits.hits.length; i++) { 
     b.push(parsed.hits.hits[i]._source.reference); 
    } 
/* //I suggest using underscore module : 
    _.each(parsed.hits.hits,function(element, index, list){ 
     b.push(element._source.reference); 
    }); 
*/ 
    var response = { 
     statusCode:'200', 
     body:JSON.stringify(b), 
     headers:{'Content-Type':'application/json'} 
    };    
    callback(null, response); 
    }); 
    //:Response contained an error 
    res.on('error', function(e){/*error handling*/callback(e,null);}); 
}); 
}