在Node.js请求的响应主体之间获取未定义?

时间:2013-02-13 16:01:25

标签: javascript node.js http httprequest

开始学习Node.js,用Node.js发送POST请求:

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来自哪里?

1 个答案:

答案 0 :(得分:12)

在添加之前,您必须初始化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"