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
  });
相关推荐
m0_694845571 小时前
服务器如何配置防火墙规则开放/关闭端口?
linux·服务器·安全·云计算
降世神童1 小时前
华为云Flexus+DeepSeek征文| 使用华为云CCE容器部署Dify-LLM高可用方案的验证与测试
运维·华为云·aigc
降世神童1 小时前
华为云Flexus+DeepSeek征文| 基于华为云Dify-LLM高可用平台开发运维故障处理智能体
运维·华为云·aigc
阿巴~阿巴~1 小时前
Linux基本命令篇 —— alias命令
linux·服务器·bash
好名字更能让你们记住我2 小时前
Linux多线程(十二)之【生产者消费者模型】
linux·运维·服务器·jvm·windows·centos
门思科技2 小时前
设计可靠 LoRaWAN 设备时需要考虑的关键能力
运维·服务器·网络·嵌入式硬件·物联网
小锋学长生活大爆炸2 小时前
【知识】RPC和gRPC
服务器·网络协议·rpc
学习编程的gas3 小时前
Linux开发工具——gcc/g++
linux·运维·服务器
大大。3 小时前
van-tabbar-item选中active数据变了,图标没变
java·服务器·前端
_可乐无糖3 小时前
AWS WebRTC: 判断viewer端拉流是否稳定的算法
linux·服务器·webrtc·aws