Home > Enterprise >  HTTP Stream using Axios (Node JS)
HTTP Stream using Axios (Node JS)

Time:03-20

I'm trying to stream price data via HTTP (Don't know why they don't use websockets..) and I use axios to make normal REST API requests but I don't know how to handle 'Transfer Encoding': 'chunked' type of requests.

This code just hangs and doesn't produce any error so assume it's working but not able to process the response:

const { data } = await axios.get(`https://stream.example.com`, {headers: 
{Authorization: `Bearer ${token}`, 'Content-Type': 'application/octet- 
stream'}})

console.log(data) // execution hangs before reaching here

Appreciate your help.

WORKING SOLUTION: As pointed out from the answer below, we need to add a responseType: stream as an axios option and also add an event listener on the response.

Working code:

const response = await axios.get(`https://stream.example.com`, {
  headers: {Authorization: `Bearer ${demoToken}`}, 
  responseType: 'stream'
});

const stream = response.data
stream.on('data', data => { 
  data = data.toString()
  console.log(data) 
})

CodePudding user response:

FYI, sending the content-type header for a GET request is meaningless. The content-type header applies to the BODY of the http request and there is no body for a GET request.

With the axios() library, if you want to get direct access to the response stream, you use the responseType option to tell Axios that you want access to the raw response stream:

const response = await axios.get('https://stream.example.com', {
    headers: {Authorization: `Bearer ${token}`, 
    responseType: 'stream'
});

const stream = response.data;

stream.on('data', data => {
    console.log(data);
});

stream.on('end', () => {
    console.log("stream done");
});

Axios document reference here.

  • Related