客户端的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地址?
发布评论