首页 > 解决方案 > 使用 Hapi、axios 和 Cheerio 时 JSON 输出中的编码错误

问题描述

有一个网站(我不管理)

<meta charset="ISO-8859-1">

我正在用cheerio,axios构建一个从这个网站读取一些数据的Hapi服务器

这就是网站显示我获得的数据的方式

网站

<span class="name">DÓLAR BNA</span>

我将那个html加载到cheerio上

const response = await axios.get(url2Get);
const $ = cheerio.load(response.data.toString('ISO-8859-1'),{ decodeEntities: false });
// process with cheerio and build/send json response

但我仍然在 JSON 输出中得到这个

json输出

我也试过安装包 iconv-lite 并做

iconv.decode(Buffer.from(title), 'ISO-8859-1');

但还没有运气。感谢您的任何建议

标签: javascriptencodingcharacter-encodingcheeriohapijs

解决方案


使用 axios 并将配置选项responseEncoding设置为“二进制”,如下所示:

const response = await axios.get(url2Get, {responseEncoding: 'binary'});
const $ = cheerio.load(response.data.toString('ISO-8859-1'),{ decodeEntities: false });
// process with cheerio and build/send json response

推荐阅读