开始学习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
来自哪里?
答案 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"
。