簡體   English   中英

node.js請求返回對象

[英]node.js request returning object

這可能已經是一個愚蠢的問題,但是我的目的是返回一個名為user的對象,然后我可以正確使用它。 http node.js文檔中包含console.log,但未提及返回對象。 這是我的代碼(來自標准文檔),在這里我也嘗試分配用戶或在end方法中返回它,但始終返回false。

var options= {
    host : 'localhost',
    port : 3000,
    path : '/users?userName=Rosella.OKon56', // the rest of the url with parameters if needed
    method : 'GET' // do GET
};


callback = function(response) {
  var str = ''; 

  //another chunk of data has been recieved, so append it to `str`
  response.on('data', function (chunk) {
    str += chunk;
  });
  //the whole response has been recieved, so we just print it out here
  response.on('end', function () {
    //console.log(str);

  });

}
var req = http.request(options, callback);
req.end();

返回一些內容,然后可以將其解析為對象結構。 例如,如果返回JSON,則可以使用JSON.parse進行解析。

在這里我也嘗試分配用戶或在end方法中返回它,但它總是返回false

如果要對解析的結果進行處理,則可以從end回調中調用具有結果的函數,如下所示:

callback = function(response) {
  var str = ''; 

  //another chunk of data has been recieved, so append it to `str`
  response.on('data', function (chunk) {
    str += chunk;
  });
  //the whole response has been recieved, so we just print it out here
  response.on('end', function () {
    doSomethingWithUserObject(JSON.parse(str));
  });
}

旁注:您的代碼已成為“隱式全球性恐怖”的獵物; 您需要聲明您的callback變量。 您還依賴於自動分號插入(在函數表達式后需要一個; ,因為它不是聲明),我不建議這樣做,但有些人喜歡。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM