nodejs 获取客服端ip,以及获取ip一直都是127.0.0.1的问题

一、问题描述

在做登录日志的时候想要获取客户端的ip, 网上查了一下 通过 req.headers['x-forwarded-for'] || req.connection.remoteAddress; 获取, 结果获取了之后不管是开发环境,还是生产环境获取到的一直都是 127.0.0.1,这是因为在配置Nginx的时候配置了如下框传来的内容, 这样Nginx默认将自己的地址设置为客户端的地址。

二、解决办法

给Nginx配置加上 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 这样才能用 req.headers['x-forwarded-for'] || req.connection.remoteAddress; 获取到真实 ip 如下图

三、附上我的获取的代码

关键如下:

javascript 复制代码
try {
  let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress || 'Unknown';
  if (ip.includes(':')) {
    ip = ip.includes(':') ? ip.split(':').slice(-1)[0] : ip;
  }
  const city = new IP2Region().search(ip) ? new IP2Region().search(ip).city + new IP2Region().search(ip).isp : '';
  const os = getOS(req.headers['user-agent']);
  const browser = req.headers['user-agent'].split(' ')[0];
  const sql = `INSERT INTO logs (username, ip, city, browser, os, create_time) VALUES (?,?,?,?,?,?)`;
  const params = [user.username, ip, city, browser, os, moment().format('YYYY-MM-DD HH:mm:ss')];
  db.queryAsync(sql, params).then(_ => {
    res.send({
      code: 200,
      msg: '登录成功',
      token
    });
  });
} catch (error) {
  console.log('-------- logs error --------', error);
  res.send({
    code: 200,
    msg: error,
    token
  });
相关推荐
萧曵 丶3 分钟前
Docker 面试题
运维·docker·容器
七牛云行业应用4 分钟前
3.5s降至0.4s!Claude Code生产级连接优化与Agent实战
运维·人工智能·大模型·aigc·claude
小草cys10 分钟前
鲲鹏920服务器安装openEuler后无法联网,但物理网线已连接
运维·服务器·openeuler
Volunteer Technology17 分钟前
FastDFS+Nginx
运维·nginx
野犬寒鸦25 分钟前
从零起步学习并发编程 || 第五章:悲观锁与乐观锁的思想与实现及实战应用与问题
java·服务器·数据库·学习·语言模型
李小白2020020228 分钟前
EMMC写入/烧录逻辑
linux·运维·服务器
yixvxi40 分钟前
RFC 8659:DNS CAA资源记录
服务器·https·ssl
Trouvaille ~1 小时前
【Linux】UDP Socket编程实战(二):网络字典与回调设计
linux·运维·服务器·网络·c++·udp·操作系统
徐子元竟然被占了!!1 小时前
虚拟化技术
运维
为什么不问问神奇的海螺呢丶1 小时前
n9e categraf docker 监控配置
运维·docker·容器