如何解决React中获取响应的编码问题?

时间:2019-06-11 08:19:07

标签: javascript reactjs react-native fetch

我正在使用react native 0.48.3并从提取请求中获取响应,但我看不到它可以自行解决编码问题的任何编码问题,因为响应的内容类型为:application / json; charset = iso- 8859-1。现在,我将我的react native应用程序升级到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)
    })
  }
}

2 个答案:

答案 0 :(得分:1)

我认为您必须这样做:

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

答案 1 :(得分: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