javascript - Node.js 将 : store req. ip 表达为变量

标签 javascript node.js express networking ip

我有以下代码,可以将连接客户端的外部 IP 和端口打印到我的 http 服务器。是否可以将 ip 和 port 存储到变量中?全局声明一个变量并在 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}`);

预先感谢您的帮助!

最佳答案

我的声誉太低,所以不幸的是我无法发表评论,但我没有看到你在代码中尝试存储客户端 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)

我设置了一个时间间隔,以便我们可以查看变量是否实际上正在更新。最初,每当间隔函数运行时,它都会打印 null。但是当我向 localhost:3000 发出请求后,它会记录我的 ip 和端口,然后将其打印出来。

关于javascript - Node.js 将 : store req. ip 表达为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52883684/

相关文章:

javascript - 仅在选项卡处于事件状态时加载数据?

javascript - Jquery - 为什么我无法在 $.ajax 中访问/设置我的 var

node.js - 如何使用apollo服务器对graphQl中的数据进行排序?

javascript - Express js无法获取/注册

javascript - 有没有一个express javascript es6字符串模板引擎

javascript - 使用jquery从iframe中的url加载第n个类

node.js - 使用 Node.js 和 Express 进行 Http Post

javascript - 为什么 Express 应用程序的 use/all 方法不起作用?

node.js - 根据数据库中的信息安排 Nodemailer 电子邮件

mongodb - Mongoose : don't insert if element already stored