如何在nodejs http模块上限制从rest服务器传入的块的大小?

问题描述 投票:0回答:1

我通过使用nodejs请求模块从nodejs请求休息服务器。如果传入的数据大小超出允许的限制,我想取消流。这里的目的是确保我的网络没有被锁定。

我的代码示例如下;

var http = require("http");

async function httpRequest({
  host,
  method,
  port,
  path
} = params, data) {
  if (method.toUpperCase() === "GET") {
    let query = "";
    data = JSON.parse(data);

    for (var key in data) {
      if (data.hasOwnProperty(key)) {
        let value = data[key];
        console.log(key + " -> " + value);
        query = query
          .concat("&")
          .concat(key)
          .concat("=")
          .concat(value);
      }
    }
    if (query) {
      query = "?".concat(query.substring(1));
    }
    path = encodeURI(path.concat(query));
    console.log("path : " + path);
  }
  var opts = {
    hostname: host,
    port: port,
    path: path,
    method: method,
    timeout: 30 * 1000,
    headers: {
      "Content-Type": "application/json"
    }
  };
  return new Promise(function (resolve, reject) {
    const req = http.request(opts, function (response) {
      console.log("Status Code : " + response.statusCode);
      if (response.statusCode < 200 || response.statusCode >= 300) {
        req.end();
        return reject("Fetch data failed  = " + response.statusCode);
      }
      var str = "";
      response.on("data", function (chunk) {
        console.log("chunk : " + chunk);
        str += chunk;
        if (str.length > 256) {
          req.abort();
          reject(
            new Error(
              "The size of the incoming data is larger than the allowable limit."
            )
          );
        }
      });

      response.on("end", function () {
        console.log("\n Result from web service : ", str);
        try {
          let jsonData = JSON.parse(str);
          if (jsonData.status) {
            if (jsonData.status.toLowerCase === "success") {
              if (!("result" in jsonData)) {
                reject("Json Structure Error");
              }
            } else if (jsonData.status.toLowerCase === "error") {
              if (!jsonData.error) {
                reject("Json Structure Error");
              }
            }
            resolve(jsonData);
          } else {
            reject("Json Structure Error");
          }
        } catch (error) {
          reject("Response json error : " + error);
        }
      });
    });

    if (method.toUpperCase() !== "GET" && data) {
      req.write(data);
    }
    //req bitti
    req.on("timeout", function () {
      console.log("timeout! " + opts.timeout / 1000 + " seconds expired");
      req.abort();
    });

    req.on("error", function (err) {
      console.log("Error : " + err);
      if (err.code === "ECONNRESET") {
        req.abort();
        console.log("Timeout occurs : " + err);
        reject(new Error("Timeout occurs : " + err));
      } else if (err.code === "ENOTFOUND") {
        req.abort();
        console.log("Address cannot be reachable : " + err);
        reject(new Error("Address cannot be reachable : " + err));
      } else {
        req.abort();
        reject(new Error(err));
      }
    });
    req.end();
  });
}

let data = JSON.stringify({
  username: "monetrum",
  password: "123456",
  name: "Loremipsumdolorsitamet,consecteturadipiscingelit" +
    ".Aeneaninaliquamodio,egetfac"
});

let params = {
  host: "127.0.0.1",
  method: "GET",
  port: 3010,
  path: "/login"
};

httpRequest(params, data);

那么好。但是有一个问题。我正在控制传入的数据。我允许的数据大小不得超过256字节。但是第一次获取的块大于允许的大小。所以我的大小控制是无意义的。是否存在处理它的方法。是否可以限制块的大小。提前致谢。

javascript node.js stream node-https
1个回答
1
投票

The 'readable' event

您想使用readable事件而不是data事件:

var byteCount = 0;
var chunkSize = 32;
var maxBytes = 256;

req.on('readable', function () {
  var chunks = [];
  var data;

  while(true) {
    data = this.read(chunkSize);
    if (!data) { break; }

    byteCount += data.byteLength;
    if (byteCount > maxBytes) {
      req.abort();
      break;
    }

    chunks.push(data);
  }

  // do something with chunks
});

req.on('abort', function () {
  // do something to handle the error
});

由于你的问题非常具体,我让这个例子更加通用,希望其他人也可以从中收集它。

https://nodejs.org/api/stream.html#stream_event_readable

然而...

The Network Does't Care

但是,您将获得更多数据。 TCP数据包大小为64k。通过非千兆位以太网将MTU截断为1500字节(1.5k)。

除了关闭连接之外,没有什么可以阻止网络活动发生,除非发送的数据少于1.5k(或疯狂的网络问题),否则每个数据事件不能少于1.5k的数据发生,你无法控制).t

P.S.

我建议您使用代码编辑器,如VSCode。阅读混合了标签和空格以及不同级别的不同块的代码非常困难。它会建议可以帮助您更早发现错误并重新格式化代码的插件,以便其他人(以及您自己)更容易阅读它。

© www.soinside.com 2019 - 2024. All rights reserved.