2016-11-29 68 views
-1

我們試圖通過http請求從URL中提取JSON對象。但是,當我們試圖返回文本時,我們始終得到「未定義」。我們實現http請求的方式有問題嗎?從URL中提取JSON對象

function getUserData(email) { 
    var pathURL = "/" + email + "/data" 
    var options = { 
     host: 'localhost', 
     port: 3000, 
     path: pathURL, 
     method: 'GET', 
     headers: { 
      accept: 'application/json' 
     } 
    }; 

var x = http.request(options, function(res){ 
    console.log("Connected"); 
    res.on('data', function(data){ 
     console.log(data); 
    }); 
}); 
} 

回答

0

響應主體是數據但不返回到x

var body = [] 
request.on('data', function(chunk) { 
    body.push(chunk) 
}).on('end', function() { 
    body = Buffer.concat(body).toString() 
    // all is done, you can now use body here 
}) 
+0

我不太清楚,如果我瞭解您的意見。你能再解釋一下嗎? –

3

通過使用
x.end();
這裏一個類似的問題的參考關閉http.request()
Sending http request in node.js

嘗試登錄錯誤爲:

req.on('error', function(err){ 
    console.log('problem with request:',err.message); 
}); 

同時檢查the documentation of http library爲好。

+0

我們仍然得到了無法讀取未定義的錯誤。但是,當我們添加了x.end()行時,它會在控制檯中打印未定義和「已連接」。不確定該從哪裏出發 –

+0

嘗試記錄錯誤。將它添加到'res.on();'方法下面。 – keshavDulal