首先写好一个前台首页,一个登陆页面,一个后台首页,一个后台列表页
需要做的事,下载好express框架,然后在下载4个npm包(express-session art-template express-art-template multer),然后对app.ja中的代码稍作修改将他的引擎改为(‘express-art-template’)
app.engine('html', require('express-art-template'));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
1.登录页面,验证登录名密码是否正确,不正确则跳转回登录页
2.按照登录后缀名分为‘/’,‘/html’请求首页;‘/login.html’请求登录页,其中要做一个判断如果用户名和密码不正确要跳出弹窗并跳转至登录页;‘/list.html’列表页;
3.在JSON文件中读取数据渲染在list.html页面
4.当我们在前台页面时,我们不希望用户直接修改请求地址的后缀名就可以访问后台所以我们引入一个新的中间件,这个中间件负责判断权限,当然我们的登陆页面是不需要被设置权限的,所以我们设置一个白名单,名单之外的页面都需要判断是不是在session中如果不是跳转至登录页,最后到处插件,在index.html中调用
const url = require('url')
function auth() {
return (req, res, next) => {
//路由白名单
const whiteList = ['/login.html', '/login', 'logout']
const pathname = url.parse(req.url).pathname
if (whiteList.indexOf(pathname) === -1) {
if (!req.session.isLogin) {
return res.render('login')
}
}
next();
}
}
module.exports = auth;
index文件,
var express = require('express');
var router = express.Router();
var path = require('path')
var multer = require('multer');
var auth = require('../middleware/auth');
var fs = require('fs')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads');
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
}
})
var upload = multer({
storage: storage
})
router.use(auth())
/* GET home page. */
router.get([['/', 'index.html'], '/index.html'], function (req, res, next) {
res.render('index', {
title: '首页',
username: req.session.isLogin ? req.session.username : ''
});
});
router.get('/login.html', function (req, res) {
res.render('login')
})
router.post('/login', function (req, res) {
const username = req.body.username;
const password = req.body.password;
console.log(req.session);
if (username != 'admin' || password != '123') {
return res.send('<script>alert("用户名或密码错误"); history.back()</script>')
}
req.session.username = username;
req.session.isLogin = true;
res.redirect('/');
})
router.get('/logout', function (req, res) {
req.session.destroy();
res.redirect('/')
})
router.get('/list.html', function (req, res) {
fs.readFile(path.join(req.app.locals.ROOT, './data/data.json'), 'utf-8', (error, data) => {
const lists = JSON.parse(data);
res.render(
'list',
{
lists: lists, username: req.session.isLogin ? req.session.username : ''
})
})
})
module.exports = router;
app文件
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session')
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
app.locals.ROOT = __dirname
// view engine setup
app.engine('html', require('express-art-template'));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
const conf = {//生成session
secret: 'liyuang',
resave: false,
saveUninitialized: false,
cookie: {
secure: false,
httpOnly: true
}
}
app.use(session(conf));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
5.然后我们说添加,还是先写静态页,然后渲染到页面上,把req.body传递给一个变量,最后push进我们的数组,然后写入我们的list文件中,然后重定向回我们的list页面
router.post('/add', upload.single('avatar'), function (req, res) {
// console.log(req.body);
fs.readFile(path.join(req.app.locals.ROOT, './data/data.json'), 'utf-8', (error, data) => {
const lists = JSON.parse(data);
const na = req.body;
na.avatar = req.file.path;
lists.push(na);
fs.writeFile(path.join(req.app.locals.ROOT, './data/data.json'), JSON.stringify(lists), (error) => {
res.redirect('/list.html')
})
})
})