I have a website with a Node.js/Express backend and I need to log the visitor's IP address. It seems this should be a fairly straightforward process, however I am having continuous difficulty with it. My code is similar:
const express = require('express');
const app = express();
var port = 443;
app.get('/', function (req, res) {
var site = req.hostname; //example returns "localhost" from "localhost:8080"
var splits = site.split("."); //"split" on "periods"
var subdomain = String(splits[1])
var _host = req.headers.host;
var _userIP = req.headers['x-forwarded-for'] || req.socket.remoteAddress || null;
console.log('_userIP is: ', _userIP); //returns 'null'
//...
});
//...
// Start server...
var webServer = app.listen(process.env.PORT || port, function(request, response) { console.log(" Received request for " + new Date()); } );
console.log('Listening on port ' + port);
//...
console.log("***CREATING WEBSOCKET SERVER");
var wsServer = new WebSocketServer({
httpServer: webServer,
// You should not use autoAcceptConnections for production
// applications, as it defeats all standard cross-origin protection
// facilities built into the protocol and the browser. You should
// *always* verify the connection's origin and decide whether or not
// to accept it.
autoAcceptConnections: false
});
For guidance I am using the following source for information: "https://stackoverflow.com/questions/8107856/how-to-determine-a-users-ip-address-in-node".
My console.log statement returns "null" as the value for the '_userIP' variable...why??? As I understand ANY connection made to the server should have some sort of IP address, correct? If that is the case then the 'null' as my 'fallback' variable definition should never be assigned, however it is...
Any advice is greatly appreciated.
BTW I have also attempted assigning the '_userIP' variable to "req.ip" as:
console.log('_userIP is: ', req.ip);
...without success. I believe it returned 'undefined' if I remember correctly.
I have also tried:
_userIP = req.header('x-forwarded-for') ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
This code throws an error, I believe because the 'req.connection.socket.remoteAddress' is deprecated...?
If it makes a difference I believe this code displays "::1" if it is run on localhost...which indicates it is functional. Why would the code fail to display a user IP address when executed on a 'real' server? Is it possible my server software (Plesk) may be somehow blocking the IP address?