Express IP过滤器可用于特定路由? [英] Express ip filter for specific routes?

查看:89
本文介绍了Express IP过滤器可用于特定路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将不同的IP过滤器应用于不同的路由?

Is it possible to apply different ip filters to different routes?

例如,我希望只有123.123.123.123中的人可以访问我的服务器的/test路由,并且只有来自124.124.124.124中的人可以访问我的服务器的/路由.

For example, I want only people from 123.123.123.123 can access my server's /test route, and only people from 124.124.124.124 can access my server's / route.

我知道 express-ipfilter 可以通过IP地址限制网站访问.但是它不能将过滤器应用于特定的路由.

I know that express-ipfilter can restrict site access by IP Address. But it cannot apply the filter to specific routes.

我也知道在路由的中间添加app.use(ipfilter(ips, {}));只能对以下路由应用过滤器:

I also know that adding app.use(ipfilter(ips, {})); in the middle of the routes can apply filter only to the routes below:

var express = require('express'),
    ipfilter = require('express-ipfilter').IpFilter;

var ips = ['::ffff:127.0.0.1'];
var app = express();

app.get('/test', function(req, res) {
    res.send('test');
});

app.use(ipfilter(ips, {})); // the ipfilter only applies to the routes below

app.get('/', function(req, res) {
    res.send('Hello World');
});

app.listen(3000);

但是我想为不同的路线使用不同的过滤器.

But I want different filters for different routes.

有可能这样做吗?

推荐答案

是的,有可能.您可以执行以下操作:

Yeah, it's possible. You could do something like:

app.get('/test', function(req, res){
    var trustedIps = ['123.123.123.123'];
    var requestIP = req.connection.remoteAddress;
    if(trustedIps.indexOf(requestIP) >= 0) {
        // do stuff
    } else {
        // handle unallowed ip
    }
})

您可能需要确保requestIP的格式正确.

You may need to make sure that requestIP is correctly formatted though.

这篇关于Express IP过滤器可用于特定路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆