记录用户访问的地址 访问时间 以及ip地址

const express = require('express')
const fs = require('fs')
const connection = require('./ulits/tools')
// 目标,创建服务器,提供日志功能,记录用户的每一个请求明细
const app = express()

function getClientIp(req) {
    return req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress;
}

app.use((req,res,next)=>{
    // 输出日志
    // console.log(new Date().toLocaleString());
    // console.log(req.url);
    // console.log(getClientIp(req));
    let time =  new Date().toLocaleString()
    let url =  req.url
    let ip =  getClientIp(req) 
    // fs.appendFile('./userinfo.txt',`\n time:${time},url:${url},ip:${ip}` ,'utf8',(err)=>{
    //     console.log(err);
    // })
    let sql = `insert into fangwen (time,url,ip) values("${time}","${url}","${ip}")`
    connection.query(sql, (err, result) => {
        if (err) {
            console.log('错误',err)
        } else {
          // 做添加,result是一个对象,其中有一个属性affectedRows
          // 表示本次操作之后,影响的行数 
          console.log(result); // result就是查询结果
          console.log(result.affectedRows); // result就是查询结果
        }
    });
    res.send('访问成功')
    next()
})

app.use(express.static('public'))
app.listen(8000, ()=>{
    console.log('服务器启动了,8000');
})
// 1. 加载mysql
const mysql = require('mysql');
// 2. 创建连接对象
const connection = mysql.createConnection({
    // 对象的属性名字不能改变
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: 'root',
    database: 'node136'
});
// 3. 连接到MySQL服务器
connection.connect((err) => {
  // 如果有错误对象,表示连接失败
  if (err) return console.log('数据库连接失败')
  // 没有错误对象提示连接成功
  console.log('mysql数据库连接成功')
});
module.exports = connection

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值