如何从axios获取在node.js中接收iso-8859-1的值

问题描述 投票:0回答:2

我有以下代码:

const notifications = await axios.get(url)
const ctype = notifications.headers["content-type"];

ctype 接收“text/json; charset=iso-8859-1”

我的字符串是这样的:“'Ol� Matheus, est� pendente.',”

如何从 iso-8859-1 解码为 utf-8 而不会出现这些错误?

谢谢

node.js utf-8 character-encoding axios iso-8859-1
2个回答
11
投票

text/json; charset=iso-8859-1
不是有效的标准内容类型。
text/json
是错误的,JSON 必须是 UTF-8。

因此,至少在服务器上解决这个问题的最佳方法是首先获取一个缓冲区(axios 支持返回缓冲区吗?),将其转换为 UTF-8 字符串(唯一合法的 Javascript 字符串),然后才运行

 JSON.parse
就在上面。

伪代码:

// be warned that I don't know axios, I assume this is possible but it's
// not the right syntax, i just made it up.
const notificationsBuffer = await axios.get(url, {return: 'buffer'});

// Once you have the buffer, this line _should_ be correct.
const notifications = JSON.parse(notificationBuffer.toString('ISO-8859-1'));

0
投票

接受的答案对我不起作用,但是这个有用的评论确实:

const axios = require("axios"); // 1.4.0

const url = "https://www.w3.org/2001/06/utf-8-test/UTF-8-demo.html";

axios
  .get(url, {responseType: "arraybuffer"})
  .then(({data}) => {
    console.log(data.toString("utf-8")); // or latin-1, iso-8859-1, etc
  })
  .catch(err => console.error(err));

如果您的响应是 JSON,那么您可以通过在

JSON.parse()
之后最后调用
.toString("utf-8")
来解析该响应。

© www.soinside.com 2019 - 2024. All rights reserved.