标签:
1.现在我们来给博客添加用户头像。
假定:注册的用户根据注册时的邮箱湖区gravatar头像,未注册的用户则根据留言填的邮箱获取gravatar头像,在主页和用户也的文章标题的右侧显示作者的头像,在文章页面留言人的头像显示在留言板的右侧。
1.1 添加已经注册用户头像
我们已经引入了crypto加密模块,之前已经引用,这边就可以直接使用,首先,打开user.js,我们添加一行代码:
var crypto = require(‘crypto‘);
然后,我们将User.prototype.save()里面的代码修改为如下所示:
var md5 = crypto.createHash(‘md5‘), email_MD5 = md5.update(this.email.toLowerCase()).digest(‘hex‘), //将email转化为小写在编码 head = "http://www.gravatar.com/avatar/" + email_MD5 + "?s=48"; //增加了head头像链接键,以便后用 //要存入数据库的文档 var user = { //用户信息 name: this.name, password: this.password, email: this.email, head: head };
接下来,打开index.js,修改成如下的代码:
router.post(‘/post‘, function(req, res) { var currentUser = req.session.user, tags = [req.body.tag1, req.body.tag2], post = new Post(currentUser.name, currentUser.head, req.body.title, tags, req.body.post); post.save(function(err) { if(err) { req.flash(‘error‘, err); return res.redirect(‘/‘); } req.flash(‘success‘, ‘发布成功!‘); res.redirect(‘/‘); //发表成功即跳转到首页 }); });
然后,我们打开post.js,作出以下的修改:
function Post(name, head, title, tags, post) { this.name = name; this.head = head; this.title = title; this.tags = tags; this.post = post; }
var post = { name: this.name, head: this.head, time: time, title: this.title, post: this.post, tags: this.tags, comments: [], pv: 0 //传入pv值,并且将其赋值为0 };
最后,我们打开user.ejs和index.ejs,在h4标签后面添加如下代码:
<a href="/u/<%= post.name %>"><img src="<%= post.head %>" style="display:inline-block; width:24px; height:24px"/></a>
2. 添加未注册用户的头像:
打开index.js,修改如下所示的代码:
//留言相应页面 router.post(‘/u/:name/:day/:title‘, function (req, res) { var date = new Date(), time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + (date.getMinutes() < 10 ? ‘0‘ + date.getMinutes() : date.getMinutes()); var md5 = crypto.createHash(‘md5‘), email_MD5 = md5.update(req.body.email.toLowerCase()).digest(‘hex‘), //将email转化为小写在编码 head = "http://www.gravatar.com/avatar/" + email_MD5 + "?s=48"; //增加了head头像链接键,以便后用 var comment = { name: req.body.name, head: head, email: req.body.email, website: req.body.website, time: time, content: req.body.content }; var newComment = new Comment(req.params.name, req.params.day, req.params.title, comment); newComment.save(function (err) { if (err) { req.flash(‘error‘, err); return res.redirect(‘back‘); } req.flash(‘success‘, ‘留言成功!‘); res.redirect(‘back‘); });
});
然后打开comment.ejs,修改其中的代码如下所示:
<p>
<img src="<%= comment.head %>" style="display:inline-block; width:16px; height:16px
; box-shadow:0px 1px 4px #888;"/>
<a href="<%= comment.website %>"><%= comment.name %></a>
<span> 回复于 <%= comment.time %></span>
</p>
至此,我们就给博客添加了注册用户和未注册用户的头像显示功能。
标签:
原文地址:http://www.cnblogs.com/yuity/p/5305631.html