节点.JS请求数据长度小于内容长度中给出的数据长度

Node.JS request data length is smaller than given in Content-Length

本文关键字:数据 小于 JS 请求 节点      更新时间:2023-09-26

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

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

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,但"端"数据长度是 25,142

谁能解释一下?

问题就在这里:

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 ) );