Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch with ReadableStream as Request Body

Tags:

I'm trying to use fetch with a ReadableStream. In this example, the ReadableStream should simply repeat "Some data..." indefinitely.

fetch('/', {   method: 'POST',    body: new ReadableStream({     pull: function(controller) {       console.log('pull called!');       controller.enqueue('Some data...');     }   }) }); 

This doesn't work. While pull is executed once, no data is sent in the request body.

POST / HTTP/1.1 Host: example.com Connection: keep-alive Content-Length: 0 Origin: https://example.com User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36 Accept: */* Referer: https://example.com/ Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.8 

How can I make a ReadableStream (or any kind of stream where I can write dynamic data) usable with fetch?

Alternatively, if this isn't yet possible, could you please indicate this? Thank you.

Note: This is a more specific spin-off question from: Method for streaming data from browser to server via HTTP

like image 238
Brad Avatar asked Dec 02 '16 19:12

Brad


People also ask

How do you use ReadableStream?

The ReadableStream() constructorThe constructor takes two objects as parameters. The first object is required, and creates a model in JavaScript of the underlying source the data is being read from. The second object is optional, and allows you to specify a custom queuing strategy to use for your stream.

How do I get a response from a readable stream?

In order to access the data from a ReadableStream you need to call one of the conversion methods (docs available here). As an example: fetch('https://jsonplaceholder.typicode.com/posts/1') . then(function(response) { return response.

Is fetch http request?

The Fetch API is a modern interface that allows you to make HTTP requests to servers from web browsers. If you have worked with XMLHttpRequest ( XHR ) object, the Fetch API can perform all the tasks as the XHR object does. In addition, the Fetch API is much simpler and cleaner.


1 Answers

We're working on making this work, see https://github.com/whatwg/fetch/pull/425 for the PR to the Fetch Standard. Once that is done you can expect this to make its way into browsers (slowly).

like image 160
Anne Avatar answered Oct 16 '22 16:10

Anne