Logi
Logi

Reputation: 115

Decode and stringify/json format NodeJs HTTPS Response Body

I am getting a weird return with my response body it looks something like (in part):

�VJI��,K-�
                              �NM,Q�*)*M�Q�LQ��40�Q���K�K�MU�R
tT�IL�HM,)JU0�+�(�&��$U� T�����9�HMQH+��U004�P�UpJ,*�,��O)V02Q�QʃY�

I have been unable to decode it into a readable format. Here is part of my logic after removing my attempts to decode:

let emit = req.emit;
let body;
req.emit = function (eventName, response) {
            switch (eventName) {
                case "response": {
                    response.on("data", (d) => {
                        body += d;
                    });
            
                    response.on("end", () => {
                        console.log('Response: ', body);
                    });
                }
            }
            return emit.apply(this, arguments)
        }

How can I get the aggregated 'body' variable in string and/or JSON format?

Thanks in advance for any tips!

Upvotes: 1

Views: 622

Answers (1)

Yash Kumar Verma
Yash Kumar Verma

Reputation: 9620

you need to readup more on encoding.

let emit = req.emit;
let body;
req.emit = function (eventName, response) {
            switch (eventName) {
                case "response": {
                    response.on("data", (d) => {
                        body += d;
                    });
            
                    response.on("end", () => {
                        const data = body.toString("utf-8")
                        console.log('Response: ', data);
                    });
                }
            }
            return emit.apply(this, arguments)
        }

more about encoding:convert streamed buffers to utf8-string

Upvotes: 1

Related Questions