【问题标题】:parse HTTP request from node.js script解析来自 node.js 脚本的 HTTP 请求
【发布时间】:2012-03-10 00:08:04
【问题描述】:

我正在尝试编写一个脚本,该脚本将访问localhost 上的脚本并在 node.js 脚本中解析它。这是我到目前为止得到的:

var http = require('http');

var options = {
    host:'127.0.0.1',
    port:'80',
    path:'/index.php'
}
var a = http.get(options, function(res){
    res.on('data', function(chunk){
        console.log(chunk);
    });
    //console.log(res);
});

但这就是它返回的全部内容: <Buffer 7b 22 61 77 65 73 6f 6d 65 22 3a 22 79 65 61 68 21 22 7d>

我知道这是某种流,但我不知道如何处理它。

【问题讨论】:

    标签: php json node.js


    【解决方案1】:

    在向其添加侦听器之前,您需要将响应对象的编码设置为“ascii”、“utf8”或“base64”之一。例如:

    var a = http.get(options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function(chunk) { // no longer emits a Buffer object
            console.log(chunk);
        });
    });
    

    【讨论】:

    • 或者只使用chunk.toString()chunk.toString('utf8')
    • @AndreySidorov 这样做会破坏多字节字符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    相关资源
    最近更新 更多