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

编程入门 行业动态 更新时间:2024-10-10 21:23:37

[使用HTTP2模块时如何在Node.js中获取<a href=https://www.elefans.com/category/jswz/34/1771403.html style=客户端的IP地址?"/>

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

我想获取用户客户端的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地址?

回答如下:

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

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

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

更多推荐

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

本文发布于:2024-05-07 14:18:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1756650.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:客户端   模块   地址   如何在   IP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!