Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to POST a responseType: 'stream' in Axios?

I am attempting to edit an instance of Axios so that the response type should be a 'stream' rather than standard JSON.

It doesn't seem clear to me from other posts on S.O. how this can be accomplished.

Is this a dead-end??

My Current Axios Instance :

import axios from 'axios';
import { URL } from '../urls';
import {
  requestHandler,
  successHandler,
  errorHandler,
} from './Handlers';

const Api = axios.create({
  baseURL: `${URL}`,
  withCredentials: true,
});

Api.interceptors.request.use((request) => requestHandler(request));
Api.interceptors.response.use((response) => successHandler(response), (error) => errorHandler(error));

export default Api;

Implemented :

const query = {"selections":{"TABLE_A":["COLUMN1"]},"filters":[{"predicates":[]}],"joins":[],"sorts":[],"limit":100,"offset":0}
const response = await Api.post('/data', query);

The axios signature for post looks like this :
axios.post(url[, data[, config]])
Example 1
Example 2

This signature doesn't seem to indicate that the newly created instance of axios has a property relating to streams. Ideally, I would be able to do something like this:

const response = await Api.post(URL, responseType: 'stream', query);

or potentially :

const response = await Api(responseType: 'stream').post(URL, query);
like image 521
Torc Avatar asked Feb 03 '20 22:02

Torc


1 Answers

While it seems possible to specify a responseType of 'stream' like this :

const response = await Api({
    url: '/data',
    method: 'POST',
    responseType: 'stream',
    data: query
}); 

Axios' xhr.js file will throw this warning in the browser :

The provided value 'stream' is not a valid enum value of type XMLHttpRequestResponseType.

Digging a bit further into the documentation :
Axios Request Configuration indicates that 'stream' is an acceptable responseType. Specifically, if you take a look within axios/index.d.ts :

export type ResponseType = 
  | 'arraybuffer' 
  | 'blob' 
  | 'document' 
  | 'json' 
  | 'text' 
  | 'stream' 

However, the WHATWG spec for an XMLHttpRequest shows that 'stream' isn't valid :

enum XMLHttpRequestResponseType {
  "",
  "arraybuffer",
  "blob",
  "document",
  "json",
  "text"
};

The issue is that the XhrAdapter is used by Axios when making requests from the client-side / in the browser. If Axios is on the server-side, the HttpAdapter will be used. The XhrAdapter will need to make XMLHttpRequests but the server can make HttpRequests, so there are TONS of posts about handling streams in Node with Axios, since Node is a backend solution.

It doesn't appear to be possible to stream results with Axios on the client-side. fetch() may be the only option.

like image 127
Torc Avatar answered Oct 21 '22 18:10

Torc