Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check is nodejs connection come from localhost

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
}
like image 466
Anonymous Avatar asked Feb 24 '14 12:02

Anonymous


3 Answers

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');});
like image 121
Felix D. Avatar answered Nov 18 '22 08:11

Felix D.


The best way to do this is by using:

req.connection.remoteAddress

like image 4
Alexandre Justino Avatar answered Nov 18 '22 07:11

Alexandre Justino


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.

like image 2
estani Avatar answered Nov 18 '22 08:11

estani