最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to solve encoding problem of fetch response in React? - Stack Overflow

matteradmin4PV0评论

I was using react native 0.48.3 and getting response from fetch request i don't see any encoding problem it resolves by itself the encoding problem because the content-type of my response is : application/json;charset=iso-8859-1 . Now i upgraded my react native app to 0.59.8 i don't know why fetch doesn't resolve encoding problem anymore althought it's the same code . I have just upgraded my app . Do you have any idea ? Here is my fetch code :

export const setDocumentListDataAsync = (k, action, server) => {
 return () => {
  fetch(defineUrlForDocumentList(action, server), {
    credentials: 'include',
    headers:{
      contentType: "application/json; charset=utf-8",
    }
  })
  .then(
  (response) => {
    var contentType = response.headers.get('content-type')
    console.warn(contentType)
      return response
    }
    ).then((response) => {
      return response.json()
    }).catch((err) => {
      console.log(err)
    })
  }
}

I was using react native 0.48.3 and getting response from fetch request i don't see any encoding problem it resolves by itself the encoding problem because the content-type of my response is : application/json;charset=iso-8859-1 . Now i upgraded my react native app to 0.59.8 i don't know why fetch doesn't resolve encoding problem anymore althought it's the same code . I have just upgraded my app . Do you have any idea ? Here is my fetch code :

export const setDocumentListDataAsync = (k, action, server) => {
 return () => {
  fetch(defineUrlForDocumentList(action, server), {
    credentials: 'include',
    headers:{
      contentType: "application/json; charset=utf-8",
    }
  })
  .then(
  (response) => {
    var contentType = response.headers.get('content-type')
    console.warn(contentType)
      return response
    }
    ).then((response) => {
      return response.json()
    }).catch((err) => {
      console.log(err)
    })
  }
}
Share Improve this question edited Jun 11, 2019 at 8:42 ksav 20.9k6 gold badges51 silver badges69 bronze badges asked Jun 11, 2019 at 8:19 stuuddstuudd 3693 gold badges9 silver badges18 bronze badges 9
  • so server responses does not match that you expect? when you pass Content-Type in request you just define that for request, not response. – skyboyer Commented Jun 11, 2019 at 8:52
  • ^ when you set the header to utf-8, fetch probably expects the response to be utf-8 and decodes incorrectly. – Avin Kavish Commented Jun 11, 2019 at 8:57
  • yup . So how can i force it to convert response type to utf-8 ? And do you think that the version of react js affects the manner that works fetch ? – stuudd Commented Jun 11, 2019 at 8:58
  • @Avin even when i remove headers i get the same problem – stuudd Commented Jun 11, 2019 at 9:01
  • 1 Yeah, fetch uses whatwg-fetch v1 in 0.48 and whatwg-fetch v3 in the current master branch. – Avin Kavish Commented Jun 11, 2019 at 9:28
 |  Show 4 more ments

3 Answers 3

Reset to default 1

You can use iconv-lite to deal with the iso-8859-1 encoding. Since you need to fetch an ArrayBuffer and React Native doesn't support response.arrayBuffer() you can use the XMLHttpRequest API as a workaround.

Here is an example:

import iconv from 'iconv-lite';
import { Buffer } from 'buffer';

const fetchJSON = (url) => {
    return new Promise((resolve, reject) => {
        const request = new XMLHttpRequest();

        request.onload = () => {
            if (request.status === 200) {
                resolve(JSON.parse(iconv.decode(Buffer.from(request.response), 'iso-8859-1')));
            } else {
                reject(new Error(request.statusText));
            }
        };
        request.onerror = () => reject(new Error(request.statusText));
        request.responseType = 'arraybuffer';

        request.open('GET', url);
        request.setRequestHeader('Content-type', 'application/json; charset=iso-8859-1');
        request.send();
    });
}

export const setDocumentListDataAsync = (k, action, server) => {
    return () => {
        return fetchJSON(defineUrlForDocumentList(action, server))
            .catch(error => console.log(error));
    }
}

You should also install the packages buffer and stream.

I think you have to do this :

export const setDocumentListDataAsync = (k, action, server) => {
 return () => {
  fetch(defineUrlForDocumentList(action, server), {
    credentials: 'include',
    headers:{
      contentType: "application/json; charset=utf-8",
    }
  })
  .then(
  (response) => {
    var contentType = response.headers.get('content-type')
    console.warn(contentType)
      return response.json()
    }
    ).then((myJson) => {
      console.log(JSON.stringify(myJson));
    }).catch((err) => {
      console.log(err)
    })
  }
}

Might be an old question, but this issue can be easily solved using the arrayBuffer() function of the fetch() response. Had a similar issue, where the server returns data in ISO encoding. Fetch .text() automatically converts the response to UTF-8 and that leads to encoding issues.

Full solution described here: https://schneide.blog/2018/08/08/decoding-non-utf8-server-responses-using-the-fetch-api/

Post a comment

comment list (0)

  1. No comments so far