Express ip filter for specific routes?

前端 未结 3 822
难免孤独
难免孤独 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:04

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

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

提交回复
热议问题