The CONNECT method is used to allow an HTTP/2 server to be used as a proxy for TCP/IP connections.

    A simple TCP Server:

    1. const net = require('net');
    2. const server = net.createServer((socket) => {
    3. let name = '';
    4. socket.setEncoding('utf8');
    5. socket.on('data', (chunk) => name += chunk);
    6. socket.on('end', () => socket.end(`hello ${name}`));
    7. });
    8. server.listen(8000);

    An HTTP/2 CONNECT proxy:

    1. const http2 = require('http2');
    2. const { NGHTTP2_REFUSED_STREAM } = http2.constants;
    3. const net = require('net');
    4. const proxy = http2.createServer();
    5. proxy.on('stream', (stream, headers) => {
    6. if (headers[':method'] !== 'CONNECT') {
    7. // Only accept CONNECT requests
    8. stream.close(NGHTTP2_REFUSED_STREAM);
    9. return;
    10. }
    11. const auth = new URL(`tcp://${headers[':authority']}`);
    12. // It's a very good idea to verify that hostname and port are
    13. // things this proxy should be connecting to.
    14. const socket = net.connect(auth.port, auth.hostname, () => {
    15. stream.respond();
    16. socket.pipe(stream);
    17. stream.pipe(socket);
    18. });
    19. socket.on('error', (error) => {
    20. stream.close(http2.constants.NGHTTP2_CONNECT_ERROR);
    21. });
    22. });
    23. proxy.listen(8001);

    An HTTP/2 CONNECT client:

    1. const http2 = require('http2');
    2. const client = http2.connect('http://localhost:8001');
    3. // Must not specify the ':path' and ':scheme' headers
    4. // for CONNECT requests or an error will be thrown.
    5. const req = client.request({
    6. ':method': 'CONNECT',
    7. ':authority': `localhost:${port}`
    8. });
    9. req.on('response', (headers) => {
    10. console.log(headers[http2.constants.HTTP2_HEADER_STATUS]);
    11. });
    12. let data = '';
    13. req.setEncoding('utf8');
    14. req.on('data', (chunk) => data += chunk);
    15. req.on('end', () => {
    16. console.log(`The server says: ${data}`);
    17. client.close();
    18. });
    19. req.end('Jane');