【问题标题】:throw new ERR_INVALID_ARG_TYPE('chunk',['string','Buffer'],chunk);TypeError[ERR_INVALID_ARG_TYPE]:The "chunk" arg must be type string or Bufferthrow new ERR_INVALID_ARG_TYPE('chunk',['string','Buffer'],chunk);TypeError[ERR_INVALID_ARG_TYPE]:“chunk”参数必须是字符串或缓冲区类型
【发布时间】:2019-01-26 11:34:06
【问题描述】:

我正在尝试使用 node js 服务将 .json 文件的内容获取到 angularjs 方法中。但我得到以下错误:

_http_outgoing.js:700 抛出新的 ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); ^ TypeError [ERR_INVALID_ARG_TYPE]:“块”参数必须是字符串或缓冲区类型之一。接收到的类型对象 在 ServerResponse.end (_http_outgoing.js:700:13)

这里是对应的代码片段...

角度控制器:注释行是我尝试过但失败的所有行。

var currentProcess = "process_1cA";
$scope.storestats = [];
var resAss = $resource('/procs/getstorestats');
var stats = resAss.get({
  process: currentProcess,
  date: date.getFullYear() + "" + m + "" + d
});
stats.$promise.then(function(response) {
  if (response != undefined) {
    //    var r = JSON.parse(response);
    //$scope.storestats.push(r);
    //$scope.storestats.push(r);

    //var r = JSON.parse(response);
    $scope.storestats.push(response);
    //angular.forEach(r, function(value, key) {
    //    $scope.storestats.push({key : value});
    //});
  }
});

NODEJs 服务:

httpApp.get('/procs/getstorestats', function(req, res, next) {

try {
    fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
        var msgs1 = JSON.parse(data);
        //var r  = data.toString('utf8');
        var msgs2 = JSON.stringify(msgs1);
        console.log(msgs1);
        res.end(msgs1);
    });
}
catch (err) {
    res.end(err.toString());
}});

P.S: 注释掉的行是我尝试过但失败的行。此外,节点服务代码 sn-p 中的注释行没有给出错误,并且在记录时显示正确,但控制器响应时的数据为空白。

【问题讨论】:

    标签: angularjs json node.js


    【解决方案1】:

    我在这里猜测了一下,但我认为您只需在 Node 代码中将 res.end() 更改为 res.send()。当您流式传输数据块时使用“end”方法,然后在您完成所有操作后调用end()。 “send”方法是一次性发送响应,让 Node 处理流。

    另外,请确保您发送回字符串!

    httpApp.get('/procs/getstorestats', function(req, res, next) {
    
      try {
        fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
            var msgs1 = JSON.parse(data);
            //var r  = data.toString('utf8');
            var msgs2 = JSON.stringify(msgs1);
            console.log(msgs1);
            res.send(msgs2);  // NOTE THE CHANGE to `msg2` (the string version)
        });
      }
      catch (err) {
        res.send(err.toString());  // NOTE THE CHANGE
      }
    });
    

    【讨论】:

    • @jakarella,你所说的发送字符串是正确的,再加上另一个变化。我会将其发布为答案。感谢您的帮助。
    【解决方案2】:

    想通了。需要进行 2 处小改动。在控制器中进行一处改动,即使用“$resource.query”而不是“$resource.get”。正如@jakarella 所说,在服务中,必须使用 .end(); 中的字符串化部分;

    控制器:

                    var resAss = $resource('/procs/getstorestats');
                    var stats =  resAss.query({process: currentProcess, date: date.getFullYear() + "" + m + "" + d});
                    stats.$promise.then(function (response) {
                        $scope.storestats.push(response);
                    }
    

    节点服务:

    httpApp.get('/procs/getstorestats', function(req, res, next) {
    
    try {
        fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
            var msgs1 = JSON.parse(data);
            var msgs2 = JSON.stringify(msgs1);
            console.log(msgs2);
            res.end(msgs2);
        });
    }
    

    【讨论】:

      【解决方案3】:

      我遇到了类似的错误。这是因为我将 process.pid 传递给 res.end()。当我将 process.pid 更改为 string 时它起作用了

      res.end(process.pid.toString());
      

      【讨论】:

        【解决方案4】:

        如果您使用“request-promise”库,请设置 json

        var options = {
            uri: 'https://api.github.com/user/repos',
            qs: {
                access_token: 'xxxxx xxxxx' 
            },
            headers: {
                'User-Agent': 'Request-Promise'
            },
            json: true // Automatically parses the JSON string in the response
        };
        
        rp(options)
            .then(function (repos) {
        
            })
            .catch(function (err) {
        
            });
        

        【讨论】:

          【解决方案5】:

          谢谢user6184932,它工作了

          try {
              await insertNewDocument(fileNameDB, taskId);
              res.end(process.pid.toString());
          } catch (error) {
              console.log("error ocurred", error);
              res.send({
                  "code": 400,
                  "failed": "error ocurred"
              })
          }
          

          【讨论】:

            【解决方案6】:

            在 mysql2 中,错误的原因是 sql 字,sql 是一个查询: const sql = select * from tableName

            pool.executeQuery({ sql, name: '给定 SRC ID 的错误列表', 值:[], errorMsg: '获取时发生错误' }) .then(数据 => {

              res.status(200).json({ data })
            })
            .catch(err => {
              console.log('\n \n ==  db , icorp fetching erro ====>  :  ', err.message, '\n \n')
            })
            

            【讨论】:

              【解决方案7】:

              我在使用Node v12 (12.14.1) 时遇到了错误。

              未捕获的 TypeError [ERR_INVALID_ARG_TYPE]:“块”参数必须是字符串或缓冲区类型之一。收到的型号

              上下文示例代码。

              const { Readable } = require('stream')
              Readable.from(Buffer.from(base64content, 'base64'))
                  .pipe( ... )
              

              解决方案(就我而言)是升级到Node v14 (14.17.3)。例如

              nvm use 14
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2021-12-24
                • 1970-01-01
                • 2022-07-13
                • 2021-08-18
                • 2021-03-16
                • 1970-01-01
                • 2020-08-12
                • 2020-10-21
                相关资源
                最近更新 更多