Chapter 4 of the original tutorial https://github.com/nswbmw/N-blog/wiki/_pages. Due to version reasons, etc., it can be implemented with slight changes based on the original tutorial.
Now, let’s add user pages and article pages to the blog.
The so-called user page means that when you click on a username link, it will jump to: domain name/u/username and list all the articles of the user.
Similarly, the article page means that when you click on the title of an article, it will jump to: domain name/u/user name/time/article name and enter the page of the article.
post.js:
Modify Post.get to Post.getAll, and modify Post.get in index.js to Post.getAll. Add the following code at the end of post.js:
//获取一篇文章Post.getOne = function(name, day, title, callback) { //打开数据库 mongodb.open(function (err, db) { if (err) { return callback(err); } //读取 posts 集合 db.collection('posts', function (err, collection) { if (err) { mongodb.close(); return callback(err); } //根据用户名、发表日期及文章名进行查询 collection.findOne({ "name": name, "time.day": day, "title": title }, function (err, doc) { mongodb.close(); if (err) { return callback(err); } console.log("333"); console.log(doc); //解析 markdown 为 html doc.post = markdown.toHTML(doc.post); console.log("444"); callback(null, doc);//返回查询的一篇文章 console.log("555"); }); }); });};
app.get('/u/:name', function (req, res) { //检查用户是否存在 User.get(req.params.name, function (err, user) { if (!user) { req.flash('error', '用户不存在!'); return res.redirect('/');//用户不存在则跳转到主页 } //查询并返回该用户的所有文章 Post.getAll(user.name, function (err, posts) { if (err) { req.flash('error', err); return res.redirect('/'); } res.render('user', { title: user.name, posts: posts, user : req.session.user, success : req.flash('success').toString(), error : req.flash('error').toString() }); }); }); }); app.get('/u/:name/:day/:title', function (req, res) { Post.getOne(req.params.name, req.params.day, req.params.title, function (err, post) { if (err) { req.flash('error', err); return res.redirect('/'); } res.render('article', { title: req.params.title, post: post, user: req.session.user, success: req.flash('success').toString(), error: req.flash('error').toString() }); }); });
<%- include header %><% posts.forEach(function (post, index) { %> <p><h2><a href="/u/<%= post.name %>/<%= post.time.day %>/<%= post.title %>"><%= post.title %></a></h2></p> <p class="info"> 作者:<a href="/u/<%= post.name %>"><%= post.name %></a> | 日期:<%= post.time.minute %> </p> <p><%- post.post %></p><% }) %><%- include footer %>
Create a new article.ejs in the blog/views/ folder and add the following code:
<%- include header %><p class="info"> 作者:<a href="/u/<%= post.name %>"><%= post.name %></a> | 日期:<%= post.time.minute %></p><p><%- post.post %></p><%- include footer %>
Click on the article title:
Click on the author: