【问题标题】:How to solve encoding problem of fetch response in React?如何解决 React 中获取响应的编码问题?
【发布时间】:2019-06-11 08:19:07
【问题描述】:

我正在使用 react native 0.48.3 并从 fetch 请求中获取响应我没有看到任何编码问题它自己解决了编码问题,因为我的响应的内容类型是: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)
    })
  }
}

【问题讨论】:

  • 所以服务器响应与您期望的不匹配?当您在请求中传递Content-Type 时,您只需将其定义为请求,而不是响应。
  • ^ 当您将标头设置为 utf-8 时,fetch 可能期望响应为 utf-8 并且解码不正确。
  • 是的。那么我怎样才能强制它将响应类型转换为 utf-8 呢?而你认为 react js 的版本会影响 fetch 的工作方式吗?
  • @Avin 即使我删除标题我也会遇到同样的问题
  • 是的,fetch 在 0.48 中使用 whatwg-fetch v1,在当前 master 分支中使用 whatwg-fetch v3。

标签: javascript reactjs react-native fetch


【解决方案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

【讨论】:

    【解决方案2】:

    我认为你必须这样做:

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

    【讨论】:

    • 谢谢mahdi 但不会改变编码问题
    • 假设服务器只支持iso-8859-1编码,无论如何;该代码无法解决问题。
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      相关资源
      最近更新 更多