Express.js:如何获取IP地址并渲染视图? [英] Express.js: How can I get the ip Address and render a view?

查看:252
本文介绍了Express.js:如何获取IP地址并渲染视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的认为这应该很容易.但是,当我渲染一个翡翠模板时,我也想获取IP地址.我的代码看起来像这样.

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

推荐答案

如果您的应用程序部署在反向代理之后,只需使用req.ip并确保您拥有app.enable('trust proxy');. Express为您提供了所有标头解析和代理逻辑.

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.

这篇关于Express.js:如何获取IP地址并渲染视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆