node.js - 使用gzip/deflate压缩轻松进行http请求

wri*_*ers 45 https gzip http deflate node.js

我试图找出如何轻松发送HTTP/HTTPS请求以及处理gzip/deflate压缩响应以及cookie的最佳方法.

我找到的最好的是https://github.com/mikeal/request,它处理压缩之外的所有内容.是否有一个模块或方法可以完成我要求的一切?

如果没有,我可以以某种方式组合请求和zlib吗?我试图将zlib和http.ServerRequest结合起来,但它失败了.

谢谢!

Rya*_*ell 98

对于最近遇到这种情况的人来说,请求库现在支持开箱即用的gzip解压缩.使用方法如下:

request(
    { method: 'GET'
    , uri: 'http://www.google.com'
    , gzip: true
    }
  , function (error, response, body) {
      // body is the decompressed response body
      console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
      console.log('the decoded data is: ' + body)
    }
  )
Run Code Online (Sandbox Code Playgroud)

来自github自述文件https://github.com/request/request

gzip - 如果为true,则添加Accept-Encoding标头以从服务器请求压缩内容编码(如果尚未存在)并解码响应中支持的内容编码.注意:对通过请求返回的正文数据(通过请求流并传递给回调函数)执行响应内容的自动解码,但不对响应流(可从响应事件获得)执行,这是未修改的http .IncomingMessage对象,可能包含压缩数据.见下面的例子.

  • 超级简单,这应该是公认的答案 (6认同)

jcr*_*nou 73

注意:自2019年起,请求内置了gzip解压缩.您仍然可以使用以下方法手动解压缩请求.

你可以简单地结合起来request,并zlib采用流.

这是一个假设您有一个服务器侦听端口8000的示例:

var request = require('request'), zlib = require('zlib');

var headers = {
    'Accept-Encoding': 'gzip'
};

request({url:'http://localhost:8000/', 'headers': headers})
    .pipe(zlib.createGunzip()) // unzip
    .pipe(process.stdout); // do whatever you want with the stream
Run Code Online (Sandbox Code Playgroud)


小智 7

这是一个枪击响应的工作示例

function gunzipJSON(response){

    var gunzip = zlib.createGunzip();
    var json = "";

    gunzip.on('data', function(data){
        json += data.toString();
    });

    gunzip.on('end', function(){
        parseJSON(json);
    });

    response.pipe(gunzip);
}
Run Code Online (Sandbox Code Playgroud)

完整代码:https://gist.github.com/0xPr0xy/5002984


Dic*_*rdt 5

http://nodejs.org/docs/v0.6.0/api/zlib.html#examples中查看示例

现在,zlib已内置到节点中。