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
  });
相关推荐
TG:@yunlaoda360 云老大2 小时前
华为云国际站代理商WeLink的资源与工具支持具体有哪些?
服务器·数据库·华为云
oMcLin2 小时前
在 Ubuntu 24.04 上安装 aaPanel 托管控制面板
linux·运维·ubuntu
"YOUDIG"2 小时前
全能安全工具箱:智能密码生成、高强度文件加密与动态二维码生成的一站式平台
服务器·网络·安全
热爱专研AI的学妹2 小时前
【高级教程】联网搜索网页阅读api使用cURL从接口调试到复杂场景实战
服务器·数据库·人工智能·搜索引擎
zhengfei6112 小时前
绿盟运维安全管理系统SQL注入漏洞
运维·sql·安全
开压路机2 小时前
Linux的权限
linux·服务器
大布布将军2 小时前
⚡后端安全基石:JWT 原理与身份验证实战
前端·javascript·学习·程序人生·安全·node.js·aigc
zly35002 小时前
在 CentOS 系统中,重启某一个网卡
linux·运维·centos
闲云一鹤2 小时前
【工具篇】使用 nvm 进行 node 版本管理
前端·npm·node.js
QT 小鲜肉3 小时前
【Linux命令大全】001.文件管理之paste命令(实操篇)
linux·运维·服务器·笔记·microsoft