15

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
}
Anonymous
  • 1,405
  • 4
  • 17
  • 26
  • 2
    You could check the [request IP](http://stackoverflow.com/q/8107856/575527) against the [server's IP](http://stackoverflow.com/questions/3653065/get-local-ip-address-in-node-js) – Joseph Feb 24 '14 at 12:17
  • End up using the `require("os")` method, helpful comment – Anonymous Feb 25 '14 at 02:05

4 Answers4

6
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');});
Felix D.
  • 2,180
  • 1
  • 23
  • 37
4

The best way to do this is by using:

req.connection.remoteAddress

Alexandre Justino
  • 1,716
  • 1
  • 19
  • 28
2

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.

estani
  • 24,254
  • 2
  • 93
  • 76
1

Check req.headers.host. If it is localhost or 127.0.0.1 use your logic to do localhost stuff. http://nodejs.org/api/http.html#http_http_incomingmessage

req.headers.host also contains the port, which you might have to clip before checking.

palanik
  • 3,601
  • 1
  • 13
  • 10