[使用HTTP2模块时如何在Node.js中获取客户端的IP地址?

问题描述 投票:1回答:1

我想获取用户客户端的IP地址。这是我的代码:

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

});

我已经阅读了node.js documentation。在那里,我找到了这个例子:

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

但是他们不使用流对象。所以我的问题是,如何在这篇文章的开头用我的代码获取客户的IP地址?

node.js node-modules http2
1个回答
0
投票

您可以尝试const ip = stream.session.socket.remoteAddress

在文档中很难找到,但是对我有用;)

[http2session_and_sockets in docs找到“ http2session.socket”一章]

© www.soinside.com 2019 - 2024. All rights reserved.