如果您想访问原始http消息,我建议使用网络模块相反,您自己编写请求。对于简单的 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);
});
});
对于发送 POST 请求application/x-www-form-urlencoded
数据,您可以使用类似以下内容编写请求:
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 是迄今为止最常见的所以这是一个非常安全的选择。