簡體   English   中英

使用 HTTP2 模塊時如何在 Node.js 中獲取客戶端的 IP 地址?

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

我想獲取用戶客戶端的 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文檔 在那里我找到了這個例子:

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 找到“http2session.socket”章節

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM