博客首页(不详细版)
- 循环索引判断类名的添加
- 去除文章内容里面所有的html标签再对字符串进行截取处理
- 文章评论功能
① 创建评论集合
// model\comment.js
// 引入mongoose模块
const mongoose = require('mongoose');
// 创建评论集合规则
const commentSchema = new mongoose.Schema({
// 文章id
aid: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Article'
},
// 评论人用户id
uid: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
// 评论时间
time: {
type: Date
},
// 评论内容
content: {
type: String
}
});
// 创建评论集合
const Comment = mongoose.model('Comment', commentSchema);
// 将评论集合构造函数作为模块成员进行导出
module.exports = {
Comment
}
② 判断用户是否登录,如果用户登录,再允许用户提交评论表单
// route\admin\login.js
// 将用户角色存储在session对象中
req.session.role = user.role;
if ( isValid ) {
// 对用户的角色进行判断
if (user.role == 'admin') {
// 重定向到用户列表页面
res.redirect('/admin/user');
} else {
// 重定向到博客首页
res.redirect('/home/');
}
// middleware\loginGuard.js
const guard = (req, res, next) => {
// 判断用户访问的是否是登录页面
// 判断用户的登录状态
// 如果用户是登录的 将请求放行
// 如果用户不是登录的 将请求重定向到登录页面
if (req.url != '/login' && !req.session.username) {
res.redirect('/admin/login');
} else {
// 如果用户是登录状态 并且是一个普通用户
if (req.session.role == 'normal') {
// 让它跳转到博客首页 阻止程序向下执行
return res.redirect('/home/')
}
// 用户是登录状态 将请求放行
next();
}
}
module.exports = guard;
// views\home\article.art
{{if userInfo}}
<h4>评论</h4>
<form class="comment-form" action="/home/comment" method="post">
<textarea class="comment" name="content"></textarea>
<input type="hidden" name="uid" value="{{@userInfo._id}}">
<input type="hidden" name="aid" value="{{@article._id}}">
<div class="items">
<input type="submit" value="提交">
</div>
</form>
{{else}}
div><h2>先进行登录,再对文章进行评论</h2></div>
{{/if}}
// route\admin\logOut.js
module.exports = (req, res) => {
// 清除模板中的用户信息
req.app.locals.userInfo = null;
});
}
③ 在服务器端创建文章评论功能对应的路由
④ 在路由请求处理函数中接收客户端传递过来的评论信息
⑤ 将评论信息存储在评论集合中
⑥ 将页面重定向回文章详情页面
// route\home.js
// 引用expess框架
const express = require('express');
// 创建博客展示页面路由
const home = express.Router();
// 博客前台首页的展示页面
home.get('/', require('./home/index'));
// 博客前台文章详情展示页面
home.get('/article', require('./home/article'));
// 创建评论功能路由
home.post('/comment', require('./home/comment'));
// 将路由对象做为模块成员进行导出
module.exports = home;
// route\home\comment.js
// 将评论集合构造函数进行导入
const { Comment } = require('../../model/comment');
module.exports = async (req, res) => {
// 接收客户端传递过来的请求参数
const { content, uid, aid } = req.body;
// 将评论信息存储到评论集合中
await Comment.create({
content: content,
uid: uid,
aid: aid,
time: new Date()
});
// 将页面重定向回文章详情页面
res.redirect('/home/article?id='+ aid);
}
⑦ 在文章详情页面路由中获取文章评论信息并展示在页面中
// route\home\article.js
// 导入文章集合构造函数
const { Article } = require('../../model/article');
// 导入评论集合构造函数
const { Comment } = require('../../model/comment');
module.exports = async (req, res) => {
// 接收客户端传递过来的文章id值
const id = req.query.id;
// 根据id查询文章详细信息
let article = await Article.findOne({_id: id}).populate('author');
// 查询当前文章所对应的评论信息
let comments = await Comment.find({aid: id}).populate('uid')
// res.send('欢迎来到博客文章详情页面')
res.render('home/article.art', { article, comments });
}