gremo
gremo

Reputation: 48899

Getting undefined in between response body with Node.js request?

Beginning learning Node.js, sending a POST request with Node.js:

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

Body shows: undefined<xml version="1.0" encoding="UTF-8">.

Where that undefined come from?

Upvotes: 1

Views: 8053

Answers (1)

freakish
freakish

Reputation: 56467

You have to initialize res.body before adding to it:

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

Otherwise you are adding to undefined which converts undefined to string "undefined".

Upvotes: 13

Related Questions