【问题标题】:how to create a HTTP-1.0 request by net.socket or http.request?如何通过 net.socket 或 http.request 创建 HTTP-1.0 请求?
【发布时间】:2012-09-14 20:48:37
【问题描述】:

我想通过 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请求!?!?
  • 因为我想创建 http 版本 1.0 而不是 1.1,你知道在 http.request 上设置请求版本的方法吗?
  • 抱歉,没去过。

标签: sockets node.js http-1.0


【解决方案1】:

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());
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 2015-02-23
    • 1970-01-01
    • 2012-08-15
    • 2020-09-13
    • 1970-01-01
    • 2019-07-06
    相关资源
    最近更新 更多