Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js: How can I get the ip Address and render a view?

I really think this should be easy. But when I render a jade template, I also want to grab the ip address. My code look like this.

app.js

app.get('/', index.home)

index.js

exports.home = function(req, res) {
    res.render('index');
};

Where can I add something like:

var ip = req.header('x-forwarded-for') || req.connection.remoteAddress; //or
console.log(req.connection.remoteAddress);
like image 917
James Teague II Avatar asked Mar 19 '23 19:03

James Teague II


1 Answers

Just use req.ip and make sure you have app.enable('trust proxy'); if your app is deployed behind a reverse proxy. Express has all the header parsing and proxy logic baked in for you.

like image 185
Peter Lyons Avatar answered Mar 31 '23 15:03

Peter Lyons