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

rslzwgfq  于 2023-10-18  发布在  iOS
关注(0)|答案(2)|浏览(162)

我有以下代码:

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

ctype接收“text/json;字符集=iso-8859-1”
我的字符串是这样的:“'老马修,还没决定',”
我怎样才能从iso-8859-1解码到utf-8而不出现错误?
谢谢

p8h8hvxi

p8h8hvxi1#

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

gdrx4gfi2#

接受的答案对我不起作用,但这条有用的评论:

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()支持的this list of encodings
然而,Node.js特有的一种更简单的方法是设置responseEncodingrequest configuration键:

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

相关问题