nodejs之获取客户端真实的ip地址+动态页面中引用静态路径下的文件及图片等内容

时间:2022-02-15 19:10:08

1、nodejs获取客户端真实的IP地址:

在一般的管理网站中,尝尝会需要将用户的一些操作记录下来,并记住是哪个用户进行操作的,这时需要用户的ip地址,但是往往当这些应用部署在服务器上后,都使用了ngix等

代理,在用户访问的时候,就需要透过代理查看用户的真实IP地址,以下是nodejs获取客户端真实IP的代码:

//获取客户端真实ip;
function getClientIp(req) {
var ipAddress;
var forwardedIpsStr = req.headers['X-Forwarded-For'];//判断是否有反向代理头信息
if (forwardedIpsStr) {//如果有,则将头信息中第一个地址拿出,该地址就是真实的客户端IP;
var forwardedIps = forwardedIpsStr.split(',');
ipAddress = forwardedIps[0];
}
if (!ipAddress) {//如果没有直接获取IP;
ipAddress = req.connection.remoteAddress;
}
return ipAddress;
};

另外,在网上看到别人有这么写的:

//代码,第一段判断是否有反向代理IP(头信息:x-forwarded-for),在判断connection的远程IP,以及后端的socket的IP。
function getClientIp(req) {
return req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
};

2、nodejs中动态页面引用静态路径下的内容

在动态页面中引用静态引入路径下的内容(如图片,css文件时),注意路径的写法:

例如:我在error.html中引用“public/images/”下的error.png图片,需要几个步骤:

工程的结构图:

nodejs之获取客户端真实的ip地址+动态页面中引用静态路径下的文件及图片等内容

第一步:app.js中:

app.use(express.static(path.join(__dirname, 'public')));//表示动态页面可引用public路径下的静态信息

第二步:error.html中:

在style中,引用背景图片时,路径前就不能再加“public/”,只能为:“images/error.png”, 因为在app.js中已经设置了动态页面只能引用public下的静态内容,且它默认就在public路径下,只需要写从public的下级目录开始写就可以了。

 <!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width initial-scale=1.0 maximum-scale=1.0 user-scalable=no" />
<title>统一支付</title>
<style>
.error-404{background-color:#EDEDF0;}
section{display: block;}
.clearfix{zoom:1;}
.module-error{margin-top:182px;}
.module-error .error-main{ margin: 0 auto;width: 420px;}
.module-error .label{float: left;width: 160px;height: 151px;background: url("images/error.png") 0 0 no-repeat;}//默认已经在public路径下,尽管改代码在IDE中报错(可以不用管)
.module-error .info{ margin-left: 182px;line-height: 1.8;}
.module-error .title{color: #666;font-size: 14px;}
.module-error .reason{margin: 8px 0 18px 0;color: #666;font-size: 12px;}
</style>
</head>
<body class="error-404">
<div id="doc_main">
<section class="bd clearfix">
<div class="module-error">
<div class="error-main clearfix">
<div class="label"></div>
<div class="info">
<h3 class="title">啊哦,你所访问的页面不存在了。</h3>
<div class="reason">
<p>可能的原因:</p>
<p>1.在地址栏中输入了错误的地址。</p>
<p>2.你点击的某个链接已过期。</p>
</div>
<div class="oper">
<p><a href="/">回到首页&gt;</a></p>
<p class="reason">或10s后将自动跳转到首页</p>
</div>
</div>
</div>
</div>
</section>
</div>
<script>
setTimeout("window.location.href='/'",10000);
</script> </body>
</html>

error.html