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

Mat*_*mes 3 utf-8 iso-8859-1 character-encoding node.js axios

我有以下代码:

const notifications = await axios.get(url)
const ctype = notifications.headers["content-type"];
Run Code Online (Sandbox Code Playgroud)

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

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

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

谢谢

Eve*_*ert 5

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'));
Run Code Online (Sandbox Code Playgroud)

  • 感谢答主!!JSON.parse 工作得很好,但我不得不从 **'ISO-8859-1'** 更改为 **latin1** 以进行语法调整。`axios({ method:'GET', url:url, responseType:'arraybuffer', }) .then(function (response) { console.log(response.data); console.log(JSON.parse(response.data) .toString('latin1'))) });` (4认同)