Encoding conversion of a fetch response

僤鯓⒐⒋嵵緔 提交于 2020-01-11 05:58:08

问题


Inside a React Native method I'm fetching a xml encoded in ISO-8859-1.

As long as the fetching is completed I'm trying to convert it to UTF-8.

Here the code:

const iconv = require('iconv-lite');

fetch('http://www.band.uol.com.br/rss/colunista_64.xml', {
      headers: {
        "Content-type": "text/xml; charset=ISO-8859-1"
      }
})
.then(res=>res.text()})
.then(text => {
   const decodedText = iconv.decode(Buffer.from(text, 'latin1'), 'latin1')
  , output = iconv.encode(decodedText, 'utf8')
   console.log(output.toString())
})

The problem is: all especial characters of the body is being replaced by "¿½"

For the conversion, I'm using the package iconv-lite

What is the better workaround for this problem?


回答1:


The best workaround is to use res.arrayBuffer() instead res.text(), as long the Buffer constructor accepts ArrayBuffer

The code:

fetch('http://www.band.uol.com.br/rss/colunista_64.xml')
      .then(res => res.arrayBuffer())
      .then(arrayBuffer => iconv.decode(new Buffer(arrayBuffer), 'iso-8859-1').toString())
      .then(converted => console.log(converted))



回答2:


As pointed out by Hellon Canella Machado you can't use res.text() and must use an ArrayBuffer as a workaround.

Since res.arrayBuffer() doesn't work with fetch in React Native you can use the XMLHttpRequest API.

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

function fetchXML() {
  return new Promise((resolve, reject) => {
    const request = new XMLHttpRequest();

    request.onload = () => {
      if (request.status === 200) {
        resolve(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', 'http://www.band.uol.com.br/rss/colunista_64.xml');
    request.setRequestHeader('Content-type', 'text/xml; charset=ISO-8859-1');
    request.send();
  });
}

fetchXML().then(response => 
    console.log(response)
);

Also make sure that you have the packages buffer and stream installed.



来源:https://stackoverflow.com/questions/41412253/encoding-conversion-of-a-fetch-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!