2013-02-13 93 views
0

開始學習Node.js的,發送POST要求用Node.js的:在響應正文與Node.js請求之間獲取undefined?

var http = require('http') 
    , https = require('https') 
    , _ = require('underscore') 
    , querystring = require('querystring');  

// Client constructor ... 

Client.prototype.request = function (options) { 
    _.extend(options, { 
     hostname: Client.API_ENDPOINT, 
     path: Client.API_PATH, 
     headers: { 
      'user-agent': this.agent 
     } 
    }); 

    var req = (this.secure ? https : http).request(options); 
    if(options.data) req.write(querystring.stringify(options.data)); 

    req.end(); 

    req.on('response', function (res) { 
     res.on('data', function (chunk) { 
      res.body += chunk; 
     }); 

     res.on('end', function() { 
      console.log(res.body); 
     }); 
    }); 
} 

體顯示:undefined<xml version="1.0" encoding="UTF-8">

undefined從哪裏來?

回答

9

你必須加入它之前初始化res.body

// some other code 
req.on('response', function (res) { 
    res.body = ""; 
    res.on('data', function (chunk) { 
     res.body += chunk; 
    }); 

    res.on('end', function() { 
     console.log(res.body); 
    }); 
}); 

否則要添加到undefined它轉換undefined字符串"undefined"

+0

我有多愚蠢?謝謝... – gremo 2013-02-13 16:05:46

+0

如果你打算把'chunk'當成一個字符串,那麼你應該添加'res.setEncoding('utf8')'。您當前的代碼可能會失敗多字節字符。 – loganfsmyth 2013-02-13 16:51:10