Node.js HTTP request returns 2 chunks (data bodies)

后端 未结 1 505
伪装坚强ぢ
伪装坚强ぢ 2021-01-17 05:33

I\'m trying to get the source of an HTML file with an HTTP request in node.js - my problem is that it returns data twice. Here is my code:

var req = http.req         


        
1条回答
  •  时光说笑
    2021-01-17 06:31

    These are not "2 data bodies", these are 2 chunks(pieces) of the same body, you have to concatenate them.

    var req = http.request(options, function(res) {
    
        var body = '';
    
        res.setEncoding('utf8');
    
        // Streams2 API
        res.on('readable', function () {
            var chunk = this.read() || '';
    
            body += chunk;
            console.log('chunk: ' + Buffer.byteLength(chunk) + ' bytes');
        });
    
        res.on('end', function () {
            console.log('body: ' + Buffer.byteLength(body) + ' bytes');
        });
    
        req.on('error', function(e) {
            console.log("error" + e.message);
        });
    });
    
    req.end();
    

    0 讨论(0)
提交回复
热议问题