【问题标题】:How can I get the value in utf-8 from an axios get receiving iso-8859-1 in node.js如何从 axios 获取 utf-8 中的值在 node.js 中接收 iso-8859-1
【发布时间】:2019-03-22 14:52:20
【问题描述】:

我有以下代码:

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


    【解决方案1】:

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

    【讨论】:

    • 感谢分析器!! JSON.parse 工作得很好,但我必须从 'ISO-8859-1' 更改为 latin1 以进行 sintaxes 调整。 axios({ method:'GET', url:url, responseType:'arraybuffer', }) .then(function (response) { console.log(response.data); console.log(JSON.parse(response.data.toString('latin1'))) });
    • 很高兴我帮助你到达那里!
    • 不错的答案,但 JavaScript 字符串是 UTF-16。
    • @TomBlodget javascript engines 可能在后台使用 UTF-16,并且存在一些泄漏的抽象...... Javascript 字符串通常是 UTF-8-ish。
    猜你喜欢
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 2011-09-23
    • 2016-07-18
    相关资源
    最近更新 更多