| To get the client IP address and user agent in a Node.js application, you can use the http or express package. 1) Using Express If you’re using Express, it’s straightforward: const express = require('express');
const app = express();
app.get('/', (req, res) => {
// Get the client's IP address
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
// Get the client's User-Agent
const userAgent = req.headers['user-agent'];
res.send(`IP Address: ${ip}, User-Agent: ${userAgent}`);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
2) Using the HTTP Module If you’re using the built-in http module: const http = require('http');
const server = http.createServer((req, res) => {
// Get the client's IP address
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
// Get the client's User-Agent
const userAgent = req.headers['user-agent'];
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(`IP Address: ${ip}, User-Agent: ${userAgent}`);
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
Notes req.headers['x-forwarded-for'] is often used to get the real IP address of the client, especially when behind a proxy or load balancer.req.connection.remoteAddress will give you the direct IP address from the connection.- The
User-Agent is available in req.headers['user-agent'].
Make sure to handle the case where x-forwarded-for might contain a list of IPs (comma-separated), with the client’s IP being the first one in the list. |