繁体   English   中英

check是nodejs连接来自localhost

[英]check is nodejs connection come from localhost

有没有办法检查nodejs连接的来源?

在我们的JavaScript中

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

但是我不知道怎么在nodejs中做,我想做(那时我只需要为git repo维护1个文件夹)

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

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

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

最好的方法是使用:

req.connection.remoteAddress

我在Express中使用ip V4是这样的:

let ipV4 = req.connection.remoteAddress.replace(/^.*:/, '');
if (ipV4 === '1') ipV4 = 'localhost';

ipV4包含调用客户端的正确值,如果它通过这种方式访问​​机器,则为==='localhost'。

您必须了解它的工作方式与浏览器中运行的js脚本不同,这是关于通过网络接口连接到服务器的客户端。

对于您描述的用例,即通过'localhost'访问,这样做。

对于其他用例,您可能需要执行更多操作,但本地意味着它正在使用计算机中的一个接口,因此您可以检查所有这些接口以进行匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM