Node.js 部落格執行個體(六)留言功能,node.js執行個體
原教程 https://github.com/nswbmw/N-blog/wiki/_pages的第六章,由於版本等的原因,在原教程基礎上稍加改動即可實現。
實現使用者給文章留言的功能,留言儲存在資料庫中。
post.js ,修改 Post.prototype.save 中要存入的文檔為:
//要存入資料庫的文檔 var post = { name: this.name, time: time, title: this.title, post: this.post, comments:[] }; 我們在文檔裡增加了 comments 鍵(數組),用來儲存此文章上的留言(一個個對象)。為了也讓留言支援 markdown 文法,我們將 Post.getOne 函數裡的:
doc.post = markdown.toHTML(doc.post); 修改為:
//解析 markdown 為 html
if (doc) {doc.comments.forEach(function (comment) {comment.content = markdown.toHTML(comment.content);});} blog/models/ 下建立 comment.js 檔案,添加如下代碼:
var mongodb = require('./db');function Comment(name, day, title, comment) {this.name = name;this.day = day;this.title = title;this.comment = comment;}module.exports = Comment;//儲存一條留言資訊Comment.prototype.save = function(callback) {var name = this.name, day = this.day, title = this.title, comment = this.comment;//開啟資料庫mongodb.open(function (err, db) {if (err) {return callback(err);}//讀取 posts 集合db.collection('posts', function (err, collection) {if (err) {mongodb.close();return callback(err);}//通過使用者名稱、時間及標題尋找文檔,並把一條留言對象添加到該文檔的 comments 數組裡collection.update({"name": name,"time.day": day,"title": title}, {$push: {"comments": comment}} ,function (err) {mongodb.close();if (err) {return callback(err);}callback(null);}); }); });};修改 index.js ,在 Post = require('../models/post.js') 後添加一行代碼:
Post=require('../models/post.js'), Comment=require('../models/comment.js');建立 comment 的視圖檔案,在 blog/views/ 檔案夾下建立 comment.ejs ,添加如下代碼:
<br /><% 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><% }) %><form method="post"><% if (user) { %> 姓名:<input type="text" name="name" value="<%= user.name %>" /><br /> 郵箱:<input type="text" name="email" value="<%= user.email %>" /><br /> 網址:<input type="text" name="website" value="/u/<%= user.name %>" /><br /><% } else { %> 姓名:<input type="text" name="name" /><br /> 郵箱:<input type="text" name="email" /><br /> 網址:<input type="text" name="website" value="http://" /><br /><% } %> <textarea name="content" rows="5" cols="80"></textarea><br /> <input type="submit" value="留言" /></form> 注意:這雷根據使用者登入狀態的不同,顯示不同的提示資訊。還需注意的一點是,未登入的使用者在留言的時候, 網址 這一項需要加上 http:// 首碼,否則在產生串連的時候會基於當前 url (本地是 localhost:3000)。
開啟article.ejs ,在 <%- include footer %> 前添加一行代碼:
<%- include comment %>
這樣我們就在文章頁面引入了留言模組。
index.js添加代碼:
app.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 comment = {name: req.body.name,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');});}); 使用 res.redirect('back'); ,即留言成功後返回到該文章頁。
看看效果:
進入部落格並登入,先發表一篇文章用來測試:
點擊進入文章可看到留言板塊,來留個言:
留言成功,再次點擊進入文章查看留言:
注意:修改代碼之後測試之前可以mongodb/blog檔案夾下的內容清空以避免出現問題
使用nodejs,實現一個簡單的介面伺服器的功可以
var http = require('http');var mysql = require('mysql');var connection = mysql.createConnection({ host : 'localhost', user : 'me', password : 'secret',});//開始你的mysql串連connection.connect();var server = http.createServer(function (req, res) {//如果你發一個GET到127.0.0.1:1337/test?a=1&b=2的話var url_info = require('url').parse(req.url, true);//檢查是不是給/test的requestif(url_info.pathname === '/test'){//把query用url encode,這樣可以用post發送var post_data = require('querystring').stringify(url_info.query);//post的optionvar post_options = {host: 'localhost',port: 1337,path: '/response_logic',method: 'POST',headers: {'Content-Type': 'application/x-www-form-urlencoded','Content-Length': post_data.length}};//發出postvar request_made = http.request(post_options, function(response_received){var buf_list = new Array();response_received.on('data',function(data){buf_list.push(data);});response_received.on('end',function(){var response_body = Buffer.concat(buf_list);res.end(response_body);connection.query('insert into .........',function(err,rows,fields){//處理你的結果});});});//發出post的datare......餘下全文>>
nodejs開發指南裡面建立微博例子中,在建立註冊賬戶的過程中報錯
就是setting.js,自己寫的一個放置資料庫設定檔的js。這不是別人寫的模組是自己建立的seting.js檔案,裡面的內容是一個json
moudule.exports = {
cookieSecret:'microblogbyvoid',
db:'microblog',
host:'localhost'
}
請參考《node.js開發指南》的P109頁。
參考資料:《node.js開發指南》