Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Fetch: characters with encoding issues

I'm trying to use Fetch to bring some data into the screen, however some of the characters ares showing a weird � sign which I believe has something to do with converting special chars.

When debugging on the server side or if I call the servlet on my browser, the problem doesn't happen, so I believe the issue is with my JavaScript. See the code below:

var myHeaders = new Headers();
myHeaders.append('Content-Type','text/plain; charset=UTF-8');

fetch('getrastreiojadlog?cod=10082551688295', myHeaders)
        .then(function (response) {
            return response.text();
        })
        .then(function (resp) {
            console.log(resp);
        });

I think it is probably some detail, but I haven't managed to find out what is happening. So any tips are welcome Thx

like image 353
Paulo Künzel Avatar asked Dec 05 '25 15:12

Paulo Künzel


1 Answers

The response's text() function always decodes the payload as utf-8.

If you want the text in other charset you may use TextDecoder to convert the response buffer (NOT the text) into a decoded text with chosen charset.

Using your example it should be:

var myHeaders = new Headers();
myHeaders.append('Content-Type','text/plain; charset=UTF-8');

fetch('getrastreiojadlog?cod=10082551688295', myHeaders)
        .then(function (response) {
            return response.arrayBuffer();
        })
        .then(function (buffer) {
            const decoder = new TextDecoder('iso-8859-1');
            const text = decoder.decode(buffer);
            console.log(text);
        });

Notice that I'm using iso-8859-1 as decoder.

Credits: Schneide Blog

like image 182
TDT Avatar answered Dec 08 '25 16:12

TDT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!