node 获取请求者的ip地址

使用 Express框架 

在 Express 中,可以使用 app.set 方法设置中间件来处理代理头。使用 trust proxy 设置告诉Express信任代理服务器发送的标头。这样,req.ip将会反映真实的客户端IP地址 

const express = require('express');
const app = express();

// 告诉Express信任代理服务器发送的标头
app.set('trust proxy', true);

app.get('/', (req, res) => {
  const ip = req.ip;
  res.send(`Your IP address is: ${ip}`);
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

使用 http 模块

const http = require('http');

const server = http.createServer((req, res) => {
  const ip = req.connection.remoteAddress;
  res.end(`Your IP address is: ${ip}`);
});

server.listen(3000, () => {
  console.log('Server is running on port 3000');
});

 

你可能感兴趣的:(node,tcp/ip,前端,javascript,node.js)