現(xiàn)在我們來給博客添加用戶頭像,注冊的用戶根據注冊時的郵箱獲取 gravatar 頭像,未注冊的用戶則根據留言填的郵箱獲取 gravatar 頭像。 什么是 gravatar ?詳情請戳:http://www.gravatar.com
我們設定:在主頁和用戶頁的文章標題右側顯示作者頭像,在文章頁面留言的人的頭像顯示在留言板左側。
我們需要用到 Node.js 中的 crypto 模塊,之前已經引入過,所以這里可以直接使用。
打開 user.js ,在最上面添加一行代碼:
var crypto = require('crypto');
然后將 User.prototype.save 內的:
var user = {
name: this.name,
password: this.password,
email: this.email
};
修改為:
var md5 = crypto.createHash('md5'),
email_MD5 = md5.update(this.email.toLowerCase()).digest('hex'),
head = "http://www.gravatar.com/avatar/" + email_MD5 + "?s=48";
//要存入數(shù)據庫的用戶信息文檔
var user = {
name: this.name,
password: this.password,
email: this.email,
head: head
};
這里我們在用戶文檔里添加了 head 鍵,方便后面使用。
注意:需要把 email 轉化成小寫再編碼。
打開 index.js ,將 app.post('/post') 中的:
post = new Post(currentUser.name, req.body.title, tags, req.body.post);
修改成:
post = new Post(currentUser.name, currentUser.head, req.body.title, tags, req.body.post);
修改 post.js ,將:
function Post(name, title, tags, post) {
this.name = name;
this.title = title;
this.tags = tags;
this.post = post;
}
修改為:
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,
time: time,
title:this.title,
tags: this.tags,
post: this.post,
comments: [],
pv: 0
};
修改為:
var post = {
name: this.name,
head: this.head,
time: time,
title:this.title,
tags: this.tags,
post: this.post,
comments: [],
pv: 0
};
最后,修改 index.ejs 和 user.ejs ,在 后添加一行代碼:
<a href="/u/<%= post.name %>"><img src="<%= post.head %>" class="r_head" /></a>
至此,我們實現(xiàn)了給已注冊的用戶添加頭像的功能。
修改 app.post('/u/:name/:day/:title'),將:
var comment = {
name: req.body.name,
email: req.body.email,
website: req.body.website,
time: time,
content: req.body.content
};
修改為:
var md5 = crypto.createHash('md5'),
email_MD5 = md5.update(req.body.email.toLowerCase()).digest('hex'),
head = "http://www.gravatar.com/avatar/" + email_MD5 + "?s=48";
var comment = {
name: req.body.name,
head: head,
email: req.body.email,
website: req.body.website,
time: time,
content: req.body.content
};
打開 comment.ejs ,將:
<% post.comments.forEach(function (comment, index) { %>
<p><a href="<%= comment.website %>"><%= comment.name %></a>
<span class="info"> 回復于 <%= comment.time %></span></p>
<p><%- comment.content %></p>
<% }) %>
修改為:
<% post.comments.forEach(function (comment, index) { %>
<div style="padding-left:4em">
<p><img src="<%= comment.head %>" class="l_head" /><a href="<%= comment.website %>"><%= comment.name %></a>
<span class="info"> 回復于 <%= comment.time %></span></p>
<p><%- comment.content %></p>
</div>
<% }) %>
最后,在 style.css 中添加兩行樣式:
.l_head{float:left;margin-left:-4em;box-shadow:0px 1px 4px #888;}
.r_head{float:right;margin-top:-2.5em;box-shadow:0px 1px 4px #888;}
現(xiàn)在,我們給博客添加了頭像的功能。