node.js proxy server posts to http server and dies when http server is closed

前端 未结 1 507
情话喂你
情话喂你 2021-01-16 04:22

I\'m sending data from client sockets through a proxy server to an http server. When I post this data from proxy server to http, everything works fine, but if I close the ht

相关标签:
1条回答
  • 2021-01-16 05:07

    Silly me, I'm not up to speed on proper error handling in node. Fixing postOut() did the trick:

    function postOut(dataToPost){
    
        var querystring = require('querystring');
        var http = require('http');
    
        var post_domain = 'localhost';
        var post_port = 8081;
        var post_path = '/';
    
        var post_data = querystring.stringify(dataToPost);
    
        var post_options = {
          host: post_domain,
          port: post_port,
          path: post_path,
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': post_data.length
          }
        };
    
        var post_req = http.request(post_options, function(res) {
          res.setEncoding('utf8');
          res.on('data', function (chunk) {
            console.log('Response: ' + chunk);
          });
        });
    
        // Handle various issues
        post_req.on('error', function(error) { // <-------------------------------- Yeah Buddy!!!
            console.log('ERROR' + error.message);
            // If you need to go on even if there is an error add below line
            //getSomething(i + 1);
        });
        post_req.on("response", function (response) {
            console.log(response);
        });
    
        // write parameters to post body
        post_req.write(post_data);
        post_req.end();
        request.on("response", function (response) {
            console.log(response);
        });
    }
    
    0 讨论(0)
提交回复
热议问题