检查是来自localhost的nodejs连接

有没有办法来检查nodejs连接来自哪里?

在JavaScript我们做

if (window.location.host == "localhost") { // Do whatever } 

但我不知道如何在nodejs中做到这一点,我想要做的(然后我只需要维护1个文件夹为git回购)

 if (window.location.host == "localhost"){ // connect to localhost mongodb }else{ // connect to mongodb uri } 

检查req.headers.host 。 如果是本地主机或127.0.0.1使用你的逻辑做本地主机的东西。 http://nodejs.org/api/http.html#http_http_incomingmessage

req.headers.host还包含端口,在检查之前,您可能必须剪切该端口。

 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');}); 

最好的办法是使用:

req.connection.remoteAddress