在写一个小dome的时候,想记录一下到底是哪些ip发起了对应的请求,因此需要在服务端去获取客户端的ip,记录一下使用,node项目使用的框架是express

一、如果使用的是express框架,那么就很简单的啦

const ip = req.ip;

二、如果是走原生的

const http = require('http');
const server = http.createServer((req, res) => {
  // 获取客户端IP(考虑代理情况)
  const forwarded = req.headers['x-forwarded-for'];
  const ip = forwarded 
    ? forwarded.split(',')[0].trim() // 取第一个IP地址
    : req.socket.remoteAddress;
});

三、注意事项

如果无效果,需要在nginx稍微配置一下东西
http {
    set_real_ip_from 203.0.113.0/24; # CDN或负载均衡器的IP段 // 受信ip
    set_real_ip_from 203.0.113.0/24;     # CDN 的IP段
    set_real_ip_from 198.51.100.0/24;    # 另一个CDN的IP段
    set_real_ip_from 172.16.0.0/12;      # 内部私有网络
    set_real_ip_from 10.0.0.1;           # 特定代理服务器IP
    real_ip_header X-Forwarded-For;
    real_ip_recursive on;

    server {
        listen 80;
        server_name example.com;

        location / {
            proxy_pass http://localhost:3000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }

        access_log /var/log/nginx/access.log main;
    }
}

kkw凯凯王
42 声望2 粉丝