1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| const express = require('express'); const fs = require('fs'); const app = express(); const path = require('path');
function recordMiddleware(req,res,next){ let {url,ip} =req; console.log(`用户访问了${url},IP地址为${ip}`); fs.appendFile(path.resolve(__dirname, './access.log'), `${url} ${ip}\n`, (err) => { if (err) { console.log(err); } }); next(); }
function checkcoode(req,res,next){ let {code} = req.query; if(code === '666') next(); else res.send('验证码错误'); } app.use(express.static(path.resolve(__dirname, './'))); app.use(recordMiddleware);
app.get('/home', checkcoode, (req, res) => { res.send('首页你好'); });
app.get('/admin', checkcoode, (req, res) => { res.send('后台管理你好'); });
app.get('*', (req, res) => { res.send('404 Not Found'); }); app.listen(3000, () => { console.log('服务器启动成功,端口号为3000'); });
|