在Node.js中设置请求标头

格兰特·赫尔曼

我一直在与node.js一起设置代理服务器,该代理服务器将处理传入的客户端请求,并将验证它们是否具有正确的证书以连接到服务器。

我要做的是能够将客户端的证书添加到其标头中,以制作出一个用户名,该用户名将传递给服务器。

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);

};

我想要做的是这样的: req.setHeader('foo','foo')

我知道它的proxy.on('proxyReq)存在,但是代码设置的方式,我需要能够使用该req参数。

有没有办法做到这一点?

如果需要澄清我的问题,请告诉我。

鲁达马努埃尔

您可以使用原始请求中提供的标头以及您想要使用的所有其他标头来编写自己的http请求,方法是使用http.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();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章