2013-02-13 63 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