javascript - 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
我会建议你改用.json
API。
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
});
推荐阅读
- c# - C#在foreach循环中修改列表项
- scala - 在 Scala 中同时访问实用程序函数
- postgresql - PostgreSQL Trigram 索引与 btree
- typescript - TypeScript:我如何打开 Maybe
类型? - docker - Docker“工件映像”与“服务映像”与“单个 FROM 映像”与“多个 FROM 映像”
- javascript - 如何从外部组件调用 Quasar 对话框?
- javascript - 使用 javascript 转换为 json 的类 Unix 路径
- python - 错误:QQmlApplicationEngine 无法加载组件“网络问题”
- flutter - Flutter 执行时间过长
- angular - 如何在不手动刷新的情况下渲染 ngIf?