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