How do I know if a request is being made from a local machine using Node and / or Express?

Some other languages ​​have things like Request.IsLocal, is there an equivalent for Node and / or Express?

PS The reason I need this is because I want to use a different authentication middleware if the request is local.

+3


source to share


2 answers


I don't believe Express comes with anything like this built in, but you can check the value req.ip

and make a definition based on that.



if (req.ip === '127.0.0.1') {
    // do something
} else {
    // do something else
}

      

+1


source


The following code should work with IPv4 and IPv6 (untested). It uses the same validation that Microsoft's System.Web.HttpRequest.IsLocal uses - check that the request is from 127.0.0.1

or from the server IP . This matches IPv6 and if the server is bound to a specific IP address.



if (req.ip === '127.0.0.1' || req.ip === server.address.address) {
    // do something
} else {
    // do something else
}

      

0


source







All Articles