【问题标题】:Wrong encoding in JSON output when working with Hapi, axios and cheerio使用 Hapi、axios 和 Cheerio 时 JSON 输出中的编码错误
【发布时间】:2021-10-24 22:36:26
【问题描述】:

有一个网站(我不管理)

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

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

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

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

我在cheerio上加载该html为

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 输出中得到这个

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

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

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

【问题讨论】:

  • 我认为那只是你的终端很奇怪

标签: javascript encoding character-encoding cheerio hapijs


【解决方案1】:

使用 axios 并将配置选项 responseEncoding 设置为 'binary',如下所示:

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

【讨论】:

  • ISO-8859-1 不起作用,但 latin1 成功了。我之前使用过 responseEncoding:'binary',但剩下的一件事是将 response.data.toString('latin1') 与 decodeEntities:false 转换。谢谢@igorshmigor
猜你喜欢
  • 2021-11-10
  • 1970-01-01
  • 2017-05-30
  • 2022-12-19
  • 1970-01-01
  • 2013-05-26
  • 1970-01-01
  • 2016-04-20
  • 1970-01-01
相关资源
最近更新 更多