Express ip filter for specific routes?

前端 未结 3 824
难免孤独
难免孤独 2021-02-09 20:44

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

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

3条回答
  •  鱼传尺愫
    2021-02-09 21:26

    Warning: package express-ipfilter is now deprecated.

    You can chain middlewares (and ipFilter is a middleware). There are 2 ways to do this:

    var express = require('express'),
        ipfilter = require('express-ipfilter').IpFilter;
    
    var ips = ['::ffff:127.0.0.1'];
    var testers = ['1.2.3.4'];
    var app = express();
    
    app.get('/test', ipfilter(testers, {mode: 'allow'}), function(req, res) {
        res.send('test');
    });
    
    
    // the ipfilter only applies to the routes below  
    app.get('/', ipfilter(ips, {mode: 'allow'}), function(req, res) {
        res.send('Hello World');
    });
    
    app.listen(3000);
    

    Or qualify the use of the middleware:

    var express = require('express'),
        ipfilter = require('express-ipfilter').IpFilter;
    
    var ips = ['::ffff:127.0.0.1'];
    var testers = ['1.2.3.4'];
    var app = express();
    
    app.use('/test', ipfilter(testers, {})); // the ipfilter only applies to the routes below    
    
    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);
    

提交回复
热议问题