How to determine a user's IP address in node

后端 未结 19 1086
天命终不由人
天命终不由人 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:07

    You can stay DRY and just use node-ipware that supports both IPv4 and IPv6.

    Install:

    npm install ipware
    

    In your app.js or middleware:

    var getIP = require('ipware')().get_ip;
    app.use(function(req, res, next) {
        var ipInfo = getIP(req);
        console.log(ipInfo);
        // { clientIp: '127.0.0.1', clientIpRoutable: false }
        next();
    });
    

    It will make the best attempt to get the user's IP address or returns 127.0.0.1 to indicate that it could not determine the user's IP address. Take a look at the README file for advanced options.

提交回复
热议问题