问题
I want to get user client's IP address. This is my code:
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>');
});
I have already read the node.js documentation. There I found this example:
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);
But they don't use the stream object. So my question is, how can I get the client's IP address with my code at the very top of this post?
来源:https://stackoverflow.com/questions/57021797/how-do-i-get-the-clients-ip-address-in-node-js-when-using-the-http2-module