在Nodejs中读取原始http消息 [英] Read raw http message in Nodejs
问题描述
我正在使用http.request函数发送http请求,我想读取整个http响应,如文本;也就是原始http协议文本。可能吗?我写了下面的代码,但它没有用。
I'm sending an http request using the http.request function, and I would like to read the whole http response like text; that is, the raw http protocol text. Is it possible? I've written the below code but it's not working.
// 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消息,我建议使用网络模块,并自行编写请求。对于简单的GET请求,这样的事情是这样的:
If you want access to the raw http message, I'd suggest using the net module instead, and writing the request yourself. Something like this for a simple GET request:
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);
});
});
对于POST请求发送 application / x-www-form-urlencoded
数据,您可以使用以下内容编写请求:
For a POST request sending application/x-www-form-urlencoded
data, you could write the request using something like:
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
需要以字节为单位的长度,而不是字符。另外,请记住数据
必须是URL编码。
where I'm using Buffer.byteLength because Content-Length
requires the length in bytes, not in characters. Also, remember that data
must be URL encoded.
如果你不太了解HTTP的格式消息,那么这是一个不错的起点:
If you don't know much about the format of HTTP messages, then this is a decent place to start:
http://jmarshall.com/easy/http/
另外,如果你不知道响应的编码是什么,那么你'我必须首先解析标题,但 UTF-8是目前最常见的所以这是一个非常安全的赌注。
Also, if you don't know what the encoding of the response will be then you'll have to parse the headers first to find out, but UTF-8 is by far the most common so it's a pretty safe bet.
这篇关于在Nodejs中读取原始http消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!