Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
156
rated 0 times [  157] [ 1]  / answers: 1 / hits: 28779  / 2 Years ago, fri, march 18, 2022, 12:00:00

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 ${token}`},
responseType: 'stream'
});

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

More From » node.js

 Answers
15

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.


[#50055] Tuesday, January 18, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kenandwightb

Total Points: 241
Total Questions: 95
Total Answers: 111

Location: Jersey
Member since Fri, Oct 1, 2021
3 Years ago
;