简体   繁体   English

节点请求模块Http.IncomingMessage不发出事件

[英]Node request module Http.IncomingMessage not emitting events

According to this link: request - Node 根据此链接: request-Node

The callback argument gets 3 arguments: callback参数获得3个参数:

An error when applicable (usually from http.ClientRequest object) An http.IncomingMessage object The third is the response body (String or Buffer, or JSON object if the json option is supplied) 适用时发生错误(通常来自http.ClientRequest对象)http.IncomingMessage对象第三个是响应主体(字符串或缓冲区,或者,如果提供json选项,则为JSON对象)

Code: 码:

var r = require("request");

var options= {
    url: "http://www.example.com/" 
};

var callback = function (err, res, body) {
    if (!err && res.statusCode == 200) {
        res.on("data", function(chunk) {
            console.log("DATA : "+chunk);
        });
        res.on("finish", function() {
            console.log("FINISHED");
        });
        console.log(body);
    }
};

r(options, callback);

But in the above code, only the console.log(body) works, the event emitters don't. 但是在上面的代码中,只有console.log(body)有效,事件发射器无效。

Also, if the callback would be invoked only when the whole response is body is available, then what's the point of making the second argument as http.IncomingMessage (Readable Stream) when I can't stream it. 另外,如果仅当整个响应可用时才调用回调,那么当我无法流式传输第二个参数时,将其作为http.IncomingMessage (可读流)作为第二点有什么意义呢?

When you pass a callback like that, request buffers the entire response for you and that is what is available in body . 当您传递这样的回调时, request为您缓冲整个响应,而这是body可用的。 Because of this, that means you won't see data and such events on res , because they've already been taken care of by request . 因此,这意味着您不会在res上看到data和此类事件,因为它们已经由request

It looks like you're mixing two different ways to use the 'request' module. 看起来您正在混合使用两种不同的方式来使用“请求”模块。 Depending on preference you can use either the callback approach or the streaming approach. 根据偏好,您可以使用回调方法或流方法。

The callback approach involves passing a function as well as the options and when all the data is received it will call the callback function. 回调方法涉及传递函数以及选项,当接收到所有数据时,它将调用回调函数。

The streaming approach allows you to attach listeners to the events such as 'response'. 流方法使您可以将侦听器附加到事件(例如“响应”)。 I'm guessing you've mixed this code in from an example from receiving http requests and sending a response with a node server as I can't see any reference to 'data' and 'finish' events in the docs for the request module. 我猜您是从接收HTTP请求并通过节点服务器发送响应的示例中混入了这段代码,因为我在请求模块的文档中看不到对“数据”和“完成”事件的任何引用。

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

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