Paulo Künzel
Paulo Künzel

Reputation: 849

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

Upvotes: 18

Views: 33749

Answers (3)

TDT
TDT

Reputation: 633

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

Upvotes: 42

Paulo Künzel
Paulo Künzel

Reputation: 849

As it turns out, the problem was in how ther servlet was serving the data without explicitly informing the enconding type on the response. By adding the following line in the Java servlet:

response.setContentType("text/html;charset=UTF-8");

it was possible got get the characters in the right format.

Upvotes: 1

Nil
Nil

Reputation: 395

Maybe your server isn't returning an utf-8 encoded response, try to find which charset is used and then modify it in call headers. Maybe ISO-8859-1 :

myHeaders.append('Content-Type','text/plain; charset=ISO-8859-1');

Upvotes: 0

Related Questions