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
  });
相关推荐
VVVVWeiYee1 小时前
TCP/UDP详解(一)
运维·网络·tcp/ip·udp·信息与通信
辉长六加12 小时前
nodejs和vue安装步骤记录
前端·javascript·vue.js·npm·node.js
谢尔登2 小时前
【计算机网络】 IPV4和IPV6区别
运维·服务器·计算机网络
@Demi2 小时前
vsCode或Cursor 使用remote-ssh插件链接远程终端
服务器·ide·vscode·ssh
努力努力再努力wz2 小时前
【c++进阶系列】:万字详解多态
java·linux·运维·开发语言·c++
杭州泽沃电子科技有限公司2 小时前
工业环境电缆火灾预防的分布式光纤在线监测
运维·人工智能·科技·安全
zzz.102 小时前
Linux问答题:调优系统性能
linux·运维·云原生
Lovyk3 小时前
完整实验命令解析:从集群搭建到负载均衡配置
linux·运维·服务器
qq_341160443 小时前
文件系统挂载详细分析(《图解Linux内核》虚拟文件系统篇笔记二)
linux·服务器·笔记
Yyyy4823 小时前
MyCAT高可用
java·运维