套接字 – 如何通过net.socket或http.request创建HTTP-1.0请求?

我想通过net.socket或http.request创建HTTP-1.0请求,但我对此代码有疑问:

var http = require('http');

var options = {
   host:'google.com',
   method: 'CONNECT',
   path: 'google.com:80',
   port: 80
};

var req = http.request(options);
req.end();

req.on('connect', function(res, socket, head) {
   socket.write('GET / HTTP/1.0\r\n' +
                'Host: google.com:80\r\n' +
                '\r\n');
socket.on('data', function(chunk) {
    console.log(chunk);
});
socket.end();
});

我得到同样的错误:

events.js:66
        throw arguments[1]; // Unhandled 'error' event
                   ^
Error: Parse Error
    at Socket.socketOnData (http.js:1366:r20)
    at TCP.onread (net.js:403:27)

欢迎您的帮助.

最佳答案 http.request总是使用HTTP / 1.1,它在源代码中是硬编码的.

以下是使用普通TCP流(通过net.connect)发送HTTP / 1.0请求的代码:

var net = require('net');

var opts = {
  host: 'google.com',
  port: 80
}

var socket = net.connect(opts, function() {
  socket.end('GET / HTTP/1.0\r\n' +
             'Host: google.com\r\n' +
              '\r\n');
});

socket.on('data', function(chunk) {
  console.log(chunk.toString());
});
点赞