fetch()のPOSTでbodyをReadableStreamにできるか確認するNipp
#FetchUploadStreaming #Nipp #Piping_Server
何をするNipp?
ブラウザのJavaScriptでPOSTリクエストのBodyをストリーミングしたいが、Chromeも未対応みたいでbodyにReadStreamを使うことができない。MDNにはその仕様は含まれているので、いつか対応されるはず。それを手軽に確認するためにNippを作っておいたもの。
Nipp:
Check POST ReadableStream body support by Piping Server
おまけ
Piping Serverを使って確認している。
以下はallowHTTP1ForStreamingUpload: trueを追加した版。
code:html
<script>
const r = new ReadableStream( {
start(controller) {
controller.enqueue(new Uint8Array(65, 66, 67));
controller.close();
}
});
// (from: https://qiita.com/ryounagaoka/items/4736c225bdd86a74d59c)
const path = Math.random().toString(36).slice(-8);
const url = https://ppng.io/${path};
fetch(url, {
method: "POST",
body: r,
duplex: "half",
});
(async () => {
const res = await fetch(url);
const text = await res.text()
const readableStreamSupport = text === 'ABC';
console.log(readableStreamSupport, text);
return POST ReadableStream body support: ${readableStreamSupport};
})();
</script>
hr.icon
追記:
web.devにネットワークを使わずに確認できる方法が紹介されていた。
code:js
const supportsRequestStreams = !new Request('', {
body: new ReadableStream(),
method: 'POST',
}).headers.has('Content-Type');
参考: Streaming requests with the fetch API
ただしこの方法だとSafariでサポートしているになってしまう。
追記: ここでSafariにも対応してチェックできる方法がある: Feature detecting request stream bodies · Issue #1275 · whatwg/fetch