Search code examples
node.jsauthenticationhttp-proxyjupyter

Setting request headers in Node.js


I have been working with node.js to set up a proxy server that will handle incoming client request and will verify that they have the proper certificates to get connected to the server.

What I want to do is to be able to add the client's certificate to their header to craft a user name, that I will pass on to the server.

function (req, res) {

//Here is the client certificate in a variable 
var clientCertificate = req.socket.getPeerCertificate();

// Proxy a web request
return this.handle_proxy('web', req, res);

};

What I want to be able to do is this : req.setHeader('foo','foo')

I know that the proxy.on('proxyReq) exist, but the way the code is set up, I need to be able to use the req parameter.

Is there a way to do this?

Please let me know if I need to clarify my question.


Solution

  • You can craft your own http request with the headers provided in the original request plus any extra headers that you'd like by using http.request. Just receive the original request, copy the headers into the new request headers, add the new headers and send the new request.

    var data = [];
    var options = {
      hostname: 'www.google.com',
      port: 80,
      path: '/upload',
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': postData.length
      }
    };
    var req = http.request(options, function(res) {
    
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
        data.push(chunk);
      });
      res.on('end', function() {
        console.log(data.join(""));
    
        //send the response to your original request
    
      });
    });
    
    req.on('error', function(e) {
      console.log('problem with request: ' + e.message);
    });
    
    // Set headers here i.e. req.setHeader('Content-Type', originalReq.getHeader('Content-Type'));
    
    // write data to request body
    
    req.write(/*original request data goes here*/);
    req.end();