How do I get the client's IP address in Node.js when using the HTTP2 module?

匆匆过客 提交于 2019-12-13 17:55:13

问题


I want to get user client's IP address. This is my code:

const server = http2.createSecureServer({

  key: fs.readFileSync('localhost.key'),

  cert: fs.readFileSync('localhost.crt')

});

server.on('error', (err) => console.error(err));
server.on('stream', (stream, headers) => {
  console.log('Path:' + headers[':path']);
  console.log('User Agent:' + headers['user-agent']);
  console.log('Cookie:' +  headers.cookie);

  stream.respond({
    'content-type': 'text/html',
    ':status': 200
  });

  stream.end('<h1>Hello World</h1>');

});

I have already read the node.js documentation. There I found this example:

const http2 = require('http2');
const server = http2.createServer((req, res) => {
  const ip = req.socket.remoteAddress;
  const port = req.socket.remotePort;
  res.end(`Your IP address is ${ip} and your source port is ${port}.`);
}).listen(3000);

But they don't use the stream object. So my question is, how can I get the client's IP address with my code at the very top of this post?

来源:https://stackoverflow.com/questions/57021797/how-do-i-get-the-clients-ip-address-in-node-js-when-using-the-http2-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!