【问题标题】:Encoding issue with AxiosAxios 的编码问题
【发布时间】:2017-03-05 19:22:42
【问题描述】:

我正在获取一个带有axios 的网页,但响应的内容类型是 ISO-8859-1,而 axios 给出的结果似乎将其解析为 UTF-8,结果有损坏的字符.

我尝试转换结果编码但没有任何效果,我认为这不是因为this

例如在got库中我可以将encoding设置为null并解决这个问题,但是我想问你我可以用axios做什么来禁用自动编码或更改它?

【问题讨论】:

    标签: character-encoding axios


    【解决方案1】:

    我的做法是这样的:

    1. 使用responseTyperesponseEncoding 设置如下请求
    const response = await axios.request({
      method: 'GET',
      url: 'https://www.example.com',
      responseType: 'arraybuffer',
      responseEncoding: 'binary'
    });
    
    1. reponse.data 解码为所需格式
    let html = iso88592.decode(response.data.toString('binary'));
    

    注意:就我而言,我需要使用this 包对其进行解码。

    【讨论】:

    • 如果您必须获取 png 并保存到磁盘,它也可以很好地工作。按照@Daniel的建议设置responseTyperesponseEncoding后,您可以将response.data传递给fs.writeFile()
    • 您好,非常感谢您的帮助,我解决了您所写的问题。我是很新的编码,你能回答这些问题吗? - 我没有使用解码,只是 => $('.aditem', result.data.toString('binary')).each((i, element) => { - 最后发在这里,也说 lating1,什么有什么不同吗?-你能把从哪里开始了解这个吗?你的资源,非常感谢
    【解决方案2】:

    没有使用拦截器或其他包,我在缓冲区上得到响应:

    notifications = await axios.request({
        method: 'GET',
        url: Link,
        responseType: 'arraybuffer',
        reponseEncoding: 'binary'
    });
    

    接下来将其转换为:

    let html = notifications.data.toString('latin1');
    

    【讨论】:

      【解决方案3】:

      this github issue Matt Zabriskie 建议使用axios response interceptor,我认为这是最干净的选择。

      axios.interceptors.response.use(response => {
          let ctype = response.headers["content-type"];
          if (ctype.includes("charset=ISO-8859-1")) {
              response.data = iconv.decode(response.data, 'ISO-8859-1');
          }
          return response;
      })
      

      【讨论】:

        【解决方案4】:

        const notifications = await axios.request({
            method: 'GET',
            url: 'https://...your link',
            responseType: 'arraybuffer',
            reponseEncoding: 'binary'
        });
        
        const decoder = new TextDecoder('ISO-8859-1');
        let html = decoder.decode(notifications.data)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-05-22
          • 2011-04-13
          • 2017-11-10
          • 1970-01-01
          • 2023-04-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多