1

我正在使用 react native 0.48.3 并从获取请求中获取响应我没有看到任何编码问题它自己解决了编码问题,因为我的响应的内容类型是:application/json;charset=iso-8859-1 . 现在我将我的本机应用程序升级到 0.59.8 我不知道为什么 fetch 不再解决编码问题,尽管它是相同的代码。我刚刚升级了我的应用程序。你有什么主意吗 ?这是我的获取代码:

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)
    })
  }
}
4

3 回答 3

1

您可以使用编码iconv-lite来处理。iso-8859-1由于您需要获取 ArrayBuffer 并且 React Native 不支持response.arrayBuffer(),您可以使用XMLHttpRequest API作为解决方法。

这是一个例子:

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));
    }
}

您还应该安装软件包bufferstream.

于 2019-08-11T14:35:27.950 回答
0

我认为你必须这样做:

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)
    })
  }
}
于 2019-06-11T09:42:02.333 回答
0

可能是一个老问题,但是使用 fetch() 响应的 arrayBuffer() 函数可以轻松解决这个问题。有一个类似的问题,服务器以 ISO 编码返回数据。Fetch .text() 会自动将响应转换为 UTF-8,这会导致编码问题。

此处描述的完整解决方案:https ://schneide.blog/2018/08/08/decoding-non-utf8-server-responses-using-the-fetch-api/

于 2022-01-30T14:07:21.663 回答