在Nodejs中阅读RAW HTTP消息



我正在使用http.request函数发送http请求,我想读取整个http响应,如文本;也就是说,RAW HTTP协议文本。是否可以?我已经写了以下代码,但它不起作用。

// Set up the request
console.log('Sending request');
var post_req = http.request(post_options, function(res) {
    res.setEncoding('utf8');
    console.log('Response statusCode: ' + res.statusCode);
//    res.on('data', function (chunk) {
//        console.log('Response: ' + chunk);
//    });
//    res.on('end', function() {});
});
post_req.on('socket', function (socket) {
    var response = "";
    socket.on('data', function(chunk){
    console.log(chunk);
    });
});
// post the data
post_req.write(post_data);
post_req.end();

如果要访问原始HTTP消息,我建议您改用Net模块,然后自己编写请求。这样简单的get请求:

var net = require('net');
var host = 'stackoverflow.com',
    port = 80,
    socket = net.connect(port, host, function() {
    var request = "GET / HTTP/1.1rnHost: " + host + "rnrn",
        rawResponse = "";
    // send http request:
    socket.end(request);
    // assume utf-8 encoding:
    socket.setEncoding('utf-8');
    // collect raw http message:
    socket.on('data', function(chunk) {
        rawResponse += chunk;
    });
    socket.on('end', function(){
        console.log(rawResponse);
    });

});

对于发送application/x-www-form-urlencoded数据的发布请求,您可以使用以下内容来编写请求:

function writePOSTRequest (data, host, path) {
    return "POST " + path + " HTTP/1.1rn" +
            "Host: " + host + "rn" +
            "Content-Type: application/x-www-form-urlencodedrn" +
            "Content-Length: " + Buffer.byteLength(data) + "rnrn" +
            data + "rnrn";
}
var data = "name1=value1&name2=value2",
    request = writePOSTRequest(data, host, "/path/to/resource");

我在使用buffer.bytelength的位置,因为 Content-Length需要字节中的长度,而不是字符。另外,请记住必须编码data

如果您对HTTP消息的格式不太了解,那么这是一个不错的起点:

http://jmarshall.com/easy/http/

另外,如果您不知道响应的编码是什么,那么您必须先解析标头才能找出答案,但是UTF-8是迄今为止最常见的,所以这是一个非常安全的赌注。

streams2 and streams1在此视频中不总是能够互操作良好,请参阅"问题:streams1 and streams2 duality"。

我试图以低于流的级别收听数据,并且此代码打印了针对我的标题的RAW HTTP响应:

var http = require('http');
var raw = '';
console.log('Sending request');
var req = http.request({host: 'stackoverflow.com'}, function(res) {
  watch(res, 'res');
  res.on('end', function() {
    console.log(raw);
  });
  res.on('data', function(data) {
    // if we don't attach 'data' handler here 'end' is not called
  });
});

req.on('socket', function (socket) {
  socket.resume();
  var oldOndata = socket.ondata;
  socket.ondata = function(buf, start, end) {
    raw += buf.slice(start, end).toString();
    oldOndata.call(socket, buf, start, end);
  };
});
req.end();

假设您的环境中允许使用此类工具,您可以跑上http debug代理,例如提琴手http://www.fiddler2.com/,这使您可以检查http呼叫和响应。

最新更新