Express

const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const crypto = require('crypto');




// 生成一个 express 实例
const app = express();

// 设置视图文件存放目录
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// 设置静态文件存放目录
app.use(express.static(path.join(__dirname, 'public')));

// 解析 urlencoded 请求体必备
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 响应首页get请求
app.get('/', function(req, res) {
	res.render('index', {
		title: '首页'
	});
});

app.get('/login', function(req, res) {
	res.render('login', {
		title: '登录',
		user: req.session.user,
		page: 'login'
	});
});

app.post('/login', function(req, res) {
	let username = req.body.username,
		password = req.body.password;

	User.findOne({username:username}, function(err, user) {
		if(err) {
			console.log(err);
			return next(err);
		}
		if(!user) {
			console.log('用户不存在!');
			return res.redirect('/login');
		}
		//对密码进行md5加密
		let md5 = crypto.createHash('md5'),
			md5password = md5.update(password).digest('hex');
		if(user.password !== md5password) {
			console.log('密码错误!');
			return res.redirect('/login');
		}
		console.log('登录成功!');
		user.password = null;
		delete user.password;
		req.session.user = user;
		return res.redirect('/');
	});
});


// 开始监听3000端口号
app.listen(3000, function(req, res) {
	console.log('app is running at port 3000');
});