【发布时间】:2019-11-02 01:20:15
【问题描述】:
我正在尝试使用fetch() API 发出 POST 请求。我按照this MDN page 的建议将ReadableStream 的实例作为请求正文传递。
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]
【问题讨论】:
标签: javascript google-chrome firefox fetch