Я пытаюсь выполнить запрос POST с помощью fetch()
API. Я передаю экземпляр ReadableStream
в качестве тела запроса, как предложено на этой странице MDN .
Вместо публикации данных из потока, объект ReadableStream просто преобразуется в строку (в результате чегострока [object ReadableStream]
) и задается в качестве тела запроса (см. кадр Wireshark ниже).
Как правильно подключать потоковые API с помощью fetch?
Примечание: проверено в Chrome версии 78.0.3904.87 (Официальная сборка)(64-разрядная версия) и Firefox 70.0.1 (64-разрядная версия).
Минимальный пример:
<html>
<head></head>
<body>
<button id="btn">Button</button>
<script>
class StreamBuffer {
constructor() {
this.data = new Uint8Array(0);
this.onChunk = null;
}
addBinaryData(uint8Array) {
const newData = new Uint8Array(this.data.length + uint8Array.length);
newData.set(this.data, 0);
newData.set(uint8Array, this.data.length);
this.data = newData;
if (typeof this.onChunk === 'function') {
this.onChunk(this.data);
this.data = new Uint8Array(0);
}
}
}
class BufferedStream {
constructor(streamBuffer) {
const buffer = streamBuffer;
this.readable = new ReadableStream({
start(controller) {
buffer.onChunk = chunk => controller.enqueue(chunk);
buffer.onClose = () => controller.close();
}
});
}
}
const button = document.querySelector('#btn');
const buffer = new StreamBuffer();
const readWriter = new BufferedStream(buffer);
const readable = readWriter.readable;
button.onclick = function() {
var url = 'http://localhost:8080/endpoint';
fetch(url, {method: "POST", body: readable});
}
</script>
</body>
</html>
Из Wireshark:
Frame 4: 412 bytes on wire (3296 bits), 412 bytes captured (3296 bits) on interface 0
Null/Loopback
Internet Protocol Version 6, Src: ::1, Dst: ::1
Transmission Control Protocol, Src Port: 55785, Dst Port: 8080, Seq: 1, Ack: 1, Len: 348
Hypertext Transfer Protocol
Line-based text data: text/plain (1 lines)
[object ReadableStream]