nodejs. How to send http request trough HTTP CONNECT tunnel?

匿名 (未验证) 提交于 2019-12-03 01:46:01

问题:

There's an example of using HTTP CONNECT tunnel from node.js documentation.

  var options = {     port: 1337,     hostname: '127.0.0.1',     method: 'CONNECT',     path: 'www.google.com:80'   };    var req = http.request(options);   req.end();    req.on('connect', (res, socket, head) => {     console.log('got connected!');      // make a request over an HTTP tunnel     socket.write('GET / HTTP/1.1\r\n' +                  'Host: www.google.com:80\r\n' +                  'Connection: close\r\n' +                  '\r\n');     socket.on('data', (chunk) => {       console.log(chunk.toString());     });     socket.on('end', () => {       proxy.close();     });   }); 

Is there a way to use the socket with established tunnel with http library instead of passing http request body trough socket by myself (trough socket.write)?

回答1:

I don't think the regular http library has any proxy support, so you'll have to implement it yourself.

The request package (built on top of http) will make things a bit easier, though:

const request = require('request');  request({   url    : 'http://www.google.com',   proxy  : 'http://localhost:1337'   tunnel : true }, (err, res, body) => {   ... }); 

By specifying tunnel : true, it will also tunnel plain HTTP requests.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!