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
  });
相关推荐
江湖有缘4 分钟前
从零开始:基于Docker Compose的Kener监控面板部署全记录
运维·docker·容器
原来是猿4 分钟前
TCP Echo Server 深度解析:从单进程到线程池的演进之路(上)
服务器·网络·tcp/ip
躺不平的理查德5 分钟前
Shell逻辑判断备忘录
运维·服务器·git
月光技术杂谈6 分钟前
国内环境下安装 docker-ce 的完整步骤
运维·docker·容器
skywalk816315 分钟前
Trae生成的中文编程语言关键字(如“定“、“函“、“印“等)需要和标识符之间用 空格 隔开,以确保正确识别
服务器·开发语言·编程
焦糖玛奇朵婷25 分钟前
健身房预约小程序开发、设计
java·大数据·服务器·前端·小程序
Leida_wanglin1 小时前
工作经验-问题总结
运维
其实防守也摸鱼1 小时前
软件安全与漏洞--软件安全设计
运维·网络·安全·网络安全·密码学·需求分析·软件安全
Liangwei Lin1 小时前
LeetCode 76. 最小覆盖子串
运维·服务器
2301_815645381 小时前
node.
node.js