简体   繁体   English

在Node.js请求的响应主体之间变得不确定?

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

Beginning learning Node.js, sending a POST request with Node.js: 开始学习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);
        });
    });
}

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

Where that undefined come from? undefined从哪里来?

You have to initialize res.body before adding to it: 您必须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);
    });
});

Otherwise you are adding to undefined which converts undefined to string "undefined" . 否则,你要添加到undefined它转换undefined字符串"undefined"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM