nodejs 获取客服端ip,以及获取ip一直都是127.0.0.1的问题

个人博客(vue3 + nodejs + mysql )http://snows-l.sitehttp://snows-l.site

一、问题描述

在做登录日志的时候想要获取客户端的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 如下图

三、附上我的获取的代码

关键如下:

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
  });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

__冬七

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值