如何从公理中获取 utf-8 中的值,在Node.js中接收 iso-8859-1



我有以下代码:

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

ctype 接收 "text/json;字符集=ISO-8859-1">

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

如何在没有这些错误的情况下从 iso-8859-1 解码为 utf-8?

谢谢

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'));

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

const axios = require("axios"); // 1.4.0
const url = "https://www.w3.org/2006/11/mwbp-tests/test-encoding-8.html";
axios
.get(url, {responseType: "arraybuffer"})
.then(({data}) => {
console.log(data.toString("latin1"));
})
.catch(err => console.error(err));

如果您的响应是 JSON,则可以使用JSON.parse(data.toString("latin1"))来解析它。

请参阅此.toString()支持的编码列表。

但是,特定于 Node.js 的一种更简单的方法是设置responseEncoding请求配置键:

axios
.get(url, {responseEncoding: "latin1"})
.then(({data}) => {
console.log(data);
})
.catch(err => console.error(err));

由于fetch现在是 Node 18+ 和浏览器中的标准配置,下面是一个示例(错误处理和省略JSON.parse()(:

fetch(url)
.then(response => response.arrayBuffer())
.then(buffer => {
const data = new TextDecoder("iso-8859-1").decode(buffer);
console.log(data);
});

最新更新