【问题标题】:Get UTF-8 html content with Node's http.get使用 Node 的 http.get 获取 UTF-8 html 内容
【发布时间】:2015-03-15 22:37:33
【问题描述】:

我正在尝试提取给定 url 的 html 内容,并且原始内容编码是 utf-8。我得到了页面的 html,但是 html 元素中的文本以错误的格式返回(问号)。

这就是我的工作:

var parsedPath = url.parse(path);
var options = {
    host: parsedPath.host,
    path: parsedPath.path,
    headers: {
        'Accept-Charset' : 'utf-8',
    }
}

http.get(options, function (res) {
    var data = "";
    res.on('data', function (chunk) {
        data += chunk;
    });
    res.on("end", function () {
        console.log(data);
    });
}).on("error", function () {
    callback(null);
});

如何强制对返回的数据进行编码?

谢谢

【问题讨论】:

  • 客户端不能强制服务器以任何特定格式返回数据。它可以告诉它它只接受特定格式的数据,然后服务器可以选择发送回哪种格式……或者它可以完全忽略这些信息。
  • @Quentin 谢谢,所以我使用的标题是不必要的。我怎样才能对数据进行编码呢?当使用邮递员通过 GET 调用获取 html 时,数据写得很好,所以我认为有办法实现它

标签: html node.js http encoding utf-8


【解决方案1】:

像这样使用setEncoding() 方法:

http.get(options, function (res) {
    res.setEncoding('utf8');

    var data = "";
    res.on('data', function (chunk) {
        data += chunk;
    });
    res.on("end", function () {
        console.log(data);
    });
});

【讨论】:

    猜你喜欢
    • 2017-04-29
    • 2013-03-08
    • 2012-10-05
    • 1970-01-01
    • 2018-05-02
    • 2020-09-15
    • 2016-08-15
    • 2011-04-10
    • 1970-01-01
    相关资源
    最近更新 更多