我正在使用http.request函数发送http请求,我想读取整个http响应,如文本;也就是原始的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();
答案 0 :(得分:3)
如果您想要访问原始http消息,我建议您改为使用net module,并自行编写请求。对于简单的GET请求,这样的事情是这样的:
var net = require('net');
var host = 'stackoverflow.com',
port = 80,
socket = net.connect(port, host, function() {
var request = "GET / HTTP/1.1\r\nHost: " + host + "\r\n\r\n",
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
数据的POST请求,您可以使用以下内容编写请求:
function writePOSTRequest (data, host, path) {
return "POST " + path + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Content-Length: " + Buffer.byteLength(data) + "\r\n\r\n" +
data + "\r\n\r\n";
}
var data = "name1=value1&name2=value2",
request = writePOSTRequest(data, host, "/path/to/resource");
我使用Buffer.byteLength,因为Content-Length
需要以字节为单位的长度,而不是字符。另外,请记住data
必须是URL编码。
如果您不太了解HTTP消息的格式,那么这是一个不错的起点:
http://jmarshall.com/easy/http/
另外,如果你不知道响应的编码是什么,那么你必须首先解析标题才能找到答案,但是UTF-8 is by far the most common所以它很漂亮安全的赌注。
答案 1 :(得分:1)
Streams2和Streams1并不总能很好地互操作,请参阅this video中的“问题:streams1和streams2二元性”。
我尝试在比流更低的级别监听数据,这段代码为我打印带有标题的原始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();
答案 2 :(得分:0)
假设您的环境允许使用这类工具,您可以运行一个HTTP调试代理,例如Fiddler http://www.fiddler2.com/,它可以让您检查HTTP调用和响应。