首页 > 解决方案 > NodeJS http服务器未发送整个缓冲区/获取未获取整个缓冲区

问题描述

我正在发送一个包含视频文件的缓冲区res.end(buffer)(使用默认节点 http 服务器模块)。当我在我的节点程序中打印缓冲区大小时,它给了我一个特定的数字,但是在客户端,当我打印缓冲区大小时,它通常给我一个较小的数字,并且缓冲区中的视频不播放(有时,它确实会播放,在这种情况下,两个数字匹配)。这是在客户端获取缓冲区的代码:

var fetchDataByReference = (reference) => {
    const requestOptions = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({reference})
    }; let url = '/storage';
    return fetch(url, requestOptions)
        .then(res => {
            var reader = res.body.getReader();
            return reader
                .read()
                .then((result) => {
                    // When I print the result's length, it sometimes doesn't match with the length of the buffer I sent.
                    return result;
                });
        })
}

标签: javascriptnode.jshttpfetch

解决方案


reader.read()返回数据流。你需要检查它所做的数据是积极的。

function fetchStream() {
  const reader = stream.getReader();
  let charsReceived = 0;

  reader.read().then(function processText({ done, value }) {
    if (done) {
      console.log("Stream complete");
      para.textContent = value;
      return;
    }

    const chunk = value;
    // work with chunk
    return reader.read().then(processText);
  });
}

您可以在这里阅读更多内容:https ://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/getReader

我会建议你改用.jsonAPI。

fetch(url, {})
  .then((res) => res.json())
  .then((data) => console.log(data));

邮政:

async function post(url = "", data = {}) {
  const response = await fetch(url, {
    method: "POST", // *GET, POST, PUT, DELETE, etc.
    mode: "cors", // no-cors, *cors, same-origin
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data), // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

post("https://example.com/answer", { answer: 42 }).then((data) => {
  console.log(data); // JSON data parsed by `response.json()` call
});

推荐阅读