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
  });
相关推荐
爱跑马的程序员18 分钟前
Linux 如何查看文件夹的大小(du、df、ls、find)
linux·运维·ubuntu
代码AI弗森2 小时前
n8n 专题:从“自动化脚本”到“可视化工作流引擎”(自建、节点、Webhook、生产部署)
运维·自动化
像风一样自由2 小时前
android native 中的函数动态注册方式总结
android·java·服务器·安卓逆向分析·native函数动态注册·.so文件分析
oMcLin3 小时前
如何在 Ubuntu 22.04 LTS 上部署并优化 Magento 电商平台,提升高并发请求的响应速度与稳定性?
linux·运维·ubuntu
小李独爱秋3 小时前
计算机网络经典问题透视:TLS协议工作过程全景解析
运维·服务器·开发语言·网络协议·计算机网络·php
阿甘正赚.4 小时前
Linux初学
linux·运维·服务器
前端付豪4 小时前
必知 Express和 MVC
前端·node.js·全栈
特别橙的橙汁4 小时前
Node.js 调用可执行文件时的 stdout 缓冲区问题
前端·node.js·swift
CLOUD ACE4 小时前
谷歌云服务商 | 借助 BigQuery 完全托管的远程 MCP 服务器,更快地构建数据分析代理
运维·服务器
以太浮标4 小时前
华为eNSP模拟器综合实验之- VLAN-QinQ技术解析
运维·网络·华为·信息与通信