Node.js 表示:存储 req.ip 到变量

Node.js express: store req.ip to variable

我有以下代码,我可以在其中将连接客户端的外部 IP 和端口打印到我的 http 服务器。是否可以将 ip 和端口存储到变量中?全局声明一个变量并在 app.use(...) 中更改它似乎不起作用。

var port = 3000;

var express = require('express');
var app = express();
var http = require('http').Server(app);

app.use(function (req, res, next) {
    console.log(req.ip);
    console.log(req.hostname);
    console.log(req.connection.remotePort);
    next();
});

app.use(express.static(__dirname + '/'));

http.listen(port, function(){
  console.log(`Listening on http://127.0.0.1:${port}`);
});

var openURL = require('opn');
console.log("Opening Server URL")
openURL(`http://127.0.0.1:${port}`);

在此先感谢您的帮助!

在你的 http 变量下你可以声明变量

var http = require('http').Server(app);
var currentIP; // you can use "let" if you are using es6

然后您可以在函数内部执行以下操作,将变量设置为 req.ip。

currentIP = req.ip;

我的声誉太低,所以很遗憾我无法发表评论,但我没有看到您在代码中尝试存储客户端 IP 和全局端口的位置?

我不明白为什么那行不通。 我刚在本地测试过,效果很好:

var port = 3000
var express = require('express')
var app = express()
var http = require('http').Server(app)
var clientIP = null
var clientPORT = null

app.use(function (req, res, next) {
    clientIP = req.ip
    clientPORT = req.connection.remotePort
    console.log(req.ip)
    console.log(req.connection.remotePort)
    next()
})

http.listen(port, function() {
    console.log('listening')
})

setInterval(function() {
    console.log(clientIP)
    console.log(clientPORT)
}, 1000)

我设置了一个时间间隔,这样我们就可以看到变量是否真的被更新了。最初,无论何时运行 interval 函数,它都会打印 null。但是在我向 localhost:3000 发出请求后,它会记录我的 ip 和端口,然后将其打印出来。