1

开始学习 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是从哪里来的?

4

1 回答 1

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);
    });
});

否则,您将添加到undefinedwhich 转换undefined为 string "undefined"

于 2013-02-13T16:03:02.567 回答