特定于节点的IP路由器

时间:2019-01-29 08:16:36

标签: node.js express

nodejs express我一直遇到这个问题。尽管可以,但是我想做一些不确定的事情。

我正在本地主机上托管一个快速应用程序。我的本地服务器也正在运行hostapd。我有一个热点。

现在是问题所在。我有这段代码。

app.use('/', portal);
app.use('/admin', passport.login , admin);

这样我就可以访问localhost:3000localhost:3000/admin了。他们都表明我想要的。现在的问题是,使用热点的IP时是否可以将两者互换?

例如:

从热点访问时,使用IP(例如http://10.0.0.1http://10.0.0.1/admin)访问IP地址,我想按原样提供该应用程序:

app.use('/', portal);
app.use('/admin', passport.login , admin);

但是当使用localhost访问时,我想交换两个或更佳的名称,但是要删除门户并直接进入管理员:

app.use('/', passport.login , admin);

这可能吗?

2 个答案:

答案 0 :(得分:0)

如果当前IP为127.0.0.1,您可以简单地将请求从门户重定向到管理员:

function redirectIfLocalhost(req, res, next) {
    // https://expressjs.com/en/api.html#req.ip
    if (req.ip === "127.0.0.1") {
        res.redirect('/admin');
    } else {
        next();
    }
}

app.use('/',redirectIfLocalhost , portal)

不过,我真的不知道这是否可能构成安全漏洞。

编辑:

如果我很好理解,您想要更多类似这样的东西:

// Handle passeport login inside handleAdmin middleware
// But replace the next function to control the next middleware
function handleAdmin(req, res, next) {
    passeport.login(req, res, (route) => {
        if (route) next(route)
        else admin(req, res, next);
    });
}

function handlePortal(req, res, next) {
    if (req.ip === "127.0.0.1") {
        handleAdmin(req, res, next);
    } else {
        portal(req, res, next);
    }
}

function preventIfLocalhost(req, res, next) {
    if (req.ip === '127.0.0.1') {
        res.status(404).send() // To be completed or replaced
    } else {
        next();
    }
}

app.use('/', handlePortal);

app.use('/admin', preventIfLocalhost, handleAdmin);

我没有尝试我的代码,因此可能需要进行一些小修正

答案 1 :(得分:0)

您可以从请求或ip模块获取ip并创建一个新的中间件来处理请求

const ip = require('ip')

app.use('/',handleRedirection, admin);

function handleRedirection(req, res, next) {
  ip.address()==='127.0.0.1' || ip.isEqual('::1', '::0:1') ? next() : passport.login(req, res, next);
}