Simple node.js proxy by piping http server to http request

后端 未结 3 749
北恋
北恋 2020-12-08 03:31

Trying to learn more about node.js by making a simple http proxy server. The use scenario is simple: user -> proxy -> server -> proxy -> user

The following code work

相关标签:
3条回答
  • 2020-12-08 03:45

    you dont have to 'pause', just 'pipe' is ok

    var connector = http.request(options, function(res) {
      res.pipe(response, {end:true});//tell 'response' end=true
    });
    request.pipe(connector, {end:true});
    

    http request will not finish until you tell it is 'end';

    0 讨论(0)
  • 2020-12-08 03:48

    OK. Got it.

    UPDATE: NB! As reported in the comments, this example doesn't work anymore. Most probably due to the Streams2 API change (node 0.9+)

    Piping back to the client has to happen inside connector's callback as follows:

    #!/usr/bin/env node
    
    var
        url = require('url'),
        http = require('http'),
        acceptor = http.createServer().listen(3128);
    
    acceptor.on('request', function(request, response) {
        console.log('request ' + request.url);
        request.pause();
        var options = url.parse(request.url);
        options.headers = request.headers;
        options.method = request.method;
        options.agent = false;
    
        var connector = http.request(options, function(serverResponse) {
                serverResponse.pause();
                response.writeHeader(serverResponse.statusCode, serverResponse.headers);
                serverResponse.pipe(response);
                serverResponse.resume();
        });
        request.pipe(connector);
        request.resume();
    });
    
    0 讨论(0)
  • 2020-12-08 03:49

    I used the examples from this post to proxy http/s requests. Faced with the problem that cookies were lost somewhere.

    So to fix that you need to handle headers from the proxy response.

    Below the working example:

    req = service.request(options, function(res) {
        response.writeHead(res.statusCode, res.headers);
        return res.pipe(response, {end: true});
    });
    request.pipe(req, {end: true});
    
    0 讨论(0)
提交回复
热议问题