Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the value in utf-8 from an axios get receiving iso-8859-1 in node.js

I have the following code:

const notifications = await axios.get(url)
const ctype = notifications.headers["content-type"];

The ctype receives "text/json; charset=iso-8859-1"

And my string is like this: "'Ol� Matheus, est� pendente.',"

How can I decode from iso-8859-1 to utf-8 without getting those erros?

Thanks

like image 342
Matheus Gomes Avatar asked Jan 28 '23 07:01

Matheus Gomes


1 Answers

text/json; charset=iso-8859-1 is not a valid standard content-type. text/json is wrong and JSON must be UTF-8.

So the best way to get around this at least on the server, is to first get a buffer (does axios support returning buffers?), converting it to a UTF-8 string (the only legal Javascript string) and only then run JSON.parse on it.

Pseudo-code:

// be warned that I don't know axios, I assume this is possible but it's
// not the right syntax, i just made it up.
const notificationsBuffer = await axios.get(url, {return: 'buffer'});

// Once you have the buffer, this line _should_ be correct.
const notifications = JSON.parse(notificationBuffer.toString('ISO-8859-1'));
like image 82
Evert Avatar answered Jan 29 '23 20:01

Evert