【问题标题】:check is nodejs connection come from localhost检查 nodejs 连接是否来自本地主机
【发布时间】:2014-03-26 02:08:14
【问题描述】:

有没有办法检查 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
}

【问题讨论】:

标签: javascript node.js


【解决方案1】:

我在 express 中使用 ip V4,如下所示:

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

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

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

对于您描述的用例,即通过 'localhost' 访问就可以了。

对于其他用例,您可能需要做更多的事情,但 local 意味着它正在使用机器中的一个接口,因此您可以检查所有这些接口是否匹配。

【讨论】:

    【解决方案2】:

    最好的方法是使用:

    req.connection.remoteAddress

    【讨论】:

    • req.connection.remoteAddress 已弃用,请使用 req.socket.remoteAddress
    【解决方案3】:
    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');});
    

    【讨论】:

    • 如果你改变你的主机名(给你的电脑一个名字),这不起作用。
    【解决方案4】:

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

    req.headers.host 还包含端口,您可能需要在检查之前对其进行剪辑。

    【讨论】:

    • 这是相当危险的,因为任何人都可以欺骗标题。
    猜你喜欢
    • 2011-11-26
    • 1970-01-01
    • 2018-04-19
    • 2012-01-01
    • 2017-02-27
    • 2015-03-29
    • 2012-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多