我想获取用户客户端的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地址?
P.S:我已经尝试过标头['X-Forwareded-For']。它是未定义的。