Is there a way to check where the nodejs connection come from?
in javascript we do
if (window.location.host == "localhost")
{
// Do whatever
}
however I have no idea how to do it in nodejs, I want to do ( then I'll only need to maintain 1 folder for the git repo )
if (window.location.host == "localhost"){
// connect to localhost mongodb
}else{
// connect to mongodb uri
}
var os = require('os');
var database_uri;
if(os.hostname().indexOf("local") > -1)
database_uri = "mongodb://localhost/database";
else
database_uri = "mongodb://remotehost/database";
//Connect to database
mongoose.connect(database_uri,
function(err){
if(err) console.log(err);
else console.log('success');});
The best way to do this is by using:
req.connection.remoteAddress
I'm using the ip V4 in express like this:
let ipV4 = req.connection.remoteAddress.replace(/^.*:/, '');
if (ipV4 === '1') ipV4 = 'localhost';
ipV4 contains the proper value of the calling client, being === 'localhost' if it'S accessing the machine via that way.
You must understand that it works different like for a js script running in a browser, this is about a client connecting to the server via a network interface.
For your described use-case, i.e. accessing via 'localhost' this will do.
For other use-case you might need to do more than that, but local means it is using one of the interfaces from the machine, so you could check all of them for a match.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With