How to determine a user's IP address in node

后端 未结 19 1126
天命终不由人
天命终不由人 2020-11-22 12:46

How can I determine the IP address of a given request from within a controller? For example (in express):

app.post(\'/get/ip/address\', function (req, res) {         


        
19条回答
  •  一向
    一向 (楼主)
    2020-11-22 13:08

    You can use request-ip, to retrieve a user's ip address. It handles quite a few of the different edge cases, some of which are mentioned in the other answers.

    Disclosure: I created this module

    Install:

    npm install request-ip
    

    In your app:

    var requestIp = require('request-ip');
    
    // inside middleware handler
    var ipMiddleware = function(req, res, next) {
        var clientIp = requestIp.getClientIp(req); // on localhost > 127.0.0.1
        next();
    };
    

    Hope this helps

提交回复
热议问题