对于非UTF-8编码,我应该在react-native / redux fetch而不是Body.text()中使用什么?

时间:2018-06-05 12:52:27

标签: react-native react-redux fetch-api

我使用react native和redux,使用redux-thunk,使用fetch读取XML数据,几乎所有工作都正常。
这是代码:

var obj = {
  "stage": 50,
  "categories": [25, 23, 28],
  "advocates": [{
    "key": "7195",
    "label": "kallol saikia"
  }],
  "cities": [{
    "key": 390,
    "label": "Delhi"
  }, {
    "key": 6,
    "label": "Mumbai"
  }],
  "checkbox-filed": true,
  "checkbox-active": true
}


let str = 'advocates=' + obj.advocates[0].key +
          '&categories=' + obj.categories[0] + 
          'checkbox-active=' + obj['checkbox-active'] + 
          'checkbox-close=' + obj['checkbox-close'] + 
          'checkbox-filed=' + obj['checkbox-filed'] + 
          'checkbox-notFiled=' + obj['checkbox-notFiled'];

obj.cities.forEach(city=>str+= 'cities=' + city.label + '&')
str = str.substring(0,str.length-1)      
console.log(str)

 

但是,数据中有一些字符串不是UTF-8(可能是UTF-16)。

我了解iconv-lite可以提供帮助,我不应该将它与Body.text()since Body.text decodes using UTF-8一起使用。
有关如何使用iconv-lite和native native和axios的示例here,但我不知道如何在我的代码中使用它。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

如果我不是为了我自己,那么对我来说:)

解决方案是避免使用fetch(有其他限制)并使用axios(或类似的东西)。

这是我的代码:

import axios from 'axios';
import iconv from 'iconv-lite';
import { Buffer } from 'buffer';
const parseString = require('react-native-xml2js').parseString;

export const fetchData = () => {
  return (dispatch) => {
    dispatch({ type: FETCH_START });

    axios({
      method: 'get',
      url: 'https://.../file.xml',
      responseType: 'arraybuffer'
    }).then((response) => {
      const result = iconv.decode(new Buffer(response.data), 'ENCODING');
      parseString(result, function(err, data) {
        fetchSuccess(dispatch, data);
      });
    }).catch((err) => {
      fetchError(dispatch, err);
    });
  };
};