【问题标题】:Node.JS request data length is smaller than given in Content-LengthNode.JS 请求数据长度小于 Content-Length 中给定的
【发布时间】:2014-12-09 15:33:02
【问题描述】:

我的请求是多部分/表单数据

这是我读取请求数据的方式:

var data = "";

this.request.on( "data" , function( chunk ){

    data += chunk;

} );

this.request.on( "end" , function(){

    this.request.body = this.parseRequest( data );

    this.emit( "end" );

}.bind( this ) );

现在,请求的Content-Length25,981,但“on end”数据的长度为25,142

谁能解释一下?

【问题讨论】:

    标签: javascript node.js request content-length


    【解决方案1】:

    问题出在这里:

    data += chunk;

    缓冲区中的.toString() 方法破坏了二进制数据——这就是长度损失的来源。

    两种解决方案:

    1. 将块保存为缓冲区并使用它。
    2. 使用.toString('binary') 将缓冲区转换为字符串而不会丢失数据(至少在我的测试中)。

    我现在的代码:

        var buffer = [];
    
        this.request.on( "data" , function( chunk ){
            buffer.push( chunk );
        } );
    
        this.request.on( "end" , function(){
    
            buffer = Buffer.concat( buffer );
            this.request.body = this.parseRequest( buffer.toString("binary") );
            this.emit( "end" );
    
        }.bind( this ) );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 2022-10-23
      相关资源
      最近更新 更多