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

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

最新更新