javascript - 在响应正文与 Node.js 请求之间未定义?

标签 javascript node.js http httprequest

开始学习Node.js,发送POST使用 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 展示:undefined<xml version="1.0" encoding="UTF-8"> .

undefined从哪里来?

最佳答案

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

关于javascript - 在响应正文与 Node.js 请求之间未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14857654/

相关文章:

javascript - 不允许在文本输入中键入或粘贴空格,并保持文本和插入符号位置相同

javascript - 如何检查嵌入文档中的元素是否为空? Node.js 和 Mongodb

javascript - Angular JS TypeScript IHttpService 注入(inject)自定义 header 值

apache - htaccess 将所有流量从 http 重定向到 https,但也重定向到在 https 上隐藏一次的 index.php

java - 在 java 文件(.java)中使用 javascript 设置和读取/检索 cookie

javascript - 带映射插件的 Knockout.js 工作流

javascript - 粘性页脚 hack 很接近,有什么提示可以让我更接近吗?

javascript - 尝试了解 Angular 路由概念,但是当尝试重新加载页面时,没有显示任何内容。

node.js - Node 异步推送循环

node.js - 使用 React Router 的服务器端渲染 "Browser history needs a DOM"