特別說明:本實例僅在windows xp sp3系統下測試通過(其它系統未經過測試)。
<node.js開發指南>這本書,之前有評論過,但之前並不清楚express2.x與3.x會有如此大的差異,導致在寫例子的過程中痛苦不已。為了避免更多的同學在學習書的例子時,撞的頭破血流,覺得還是有必要分享一下自己這次痛苦的經歷。
講實話,學習不是特別穩定和成熟的技術風險不小,例如這個express。3.x就刪除了很多2.x的特性和功能(但好不容易買本書,書上並沒有地方特別指出版本差異的問題,導致一開始就掉進一個坑里去了)。先看看書中的2.x與目前最新版本的3.x它們之間的差異:
2.x到3.x的遷移(Migrating from 2.x to 3.x)
刪除:
1: res.render() "status" option (use node's res.statusCode= or res.status(code).render(...))
2: res.render() "charset" option (use res.charset=)
3: res.local(name, value) (use res.locals.name = value or res.locals({ name: value }) instead)
4: app.dynamicHelpers() (use middleware + res.locals)
5: app.helpers() (use app.locals)
6: the concept of a "layout" (template engine specific now)
7: partial() (template engine specific)
8: res.partial()
9: "view options" setting, use app.locals
10: "hints" setting
11: req.isXMLHttpRequest (use req.xhr)
12: app.error() (use middleware with (err, req, res, next))
13: req.flash() (just use sessions: req.session.messages = ['foo'] etc)
14: connect-flash can be used as middleware to provide req.flash()
發生發動的有:
1: req.header(field[, defaultValue]) replaced by req.get(field) (remains for backwards compatibility)
2: res.header(field[, value]) replaced by res.set(field, value) / res.get(field) (remains for backwards compatibility)
3: res.send(body[, code]) is now res.send([code,] body)
4: res.redirect(url[, code]) is now res.redirect([code,] url)
5: res.json(obj[, code]) is now res.json([code,] obj)
6: renamed app.register() to app.engine()
7: template engine compliance from engine.compile(str, options) => Function to engine.__express(filename, options, callback)
8: express.createServer() is now simply express() (but remains for BC)
9: Use express.cookieParser('secret') instead of passing the secret to the express.session() middleware. The 'secret' option in the express.session() middleware has been removed.
以前可以直接用的很多特性,如果使用Express 3.x就得安裝“插件”來支持了。
廢話不多說了,分享一下使用Express3.x來實現書中微博系統的例子。
1、使用express projectName創建項目時,express的-t參數已經失效,你得手修改package.json和app.js文件來指定模塊引擎,默認的為jade;因為jade模塊寫起來實在是讓人蛋疼不已,我強烈建議換成ejs。這樣你需要修改的文件:
app.js
package.json (使用*默認會獲取最新的)
2、connect-mongo的用法發生了變化,你需要使用下面的方法才行
1: var MongoStore = require('connect-mongo')(express);
3、3.x默認已經不支持flash了,你需要先使用npm install connect-flash。然后在app.js中添加如下代碼:
1: var flash = require('connect-flash');
2:
3: app.configure(function(){
4: app.use(flash());
5: });
注意上述的代碼,app.use(flash());要放在session之前(這個是我試出來的,原因還沒去搞明白)
4、不支持ejs模塊的partials方法,你需要使用npm install express-partials,然后在app.js中添加如下代碼:
1: var partials = require('express-partials');
2:
3: app.use(partials());
5、在使用res.render時需要顯式傳入模塊可能要用到的變量和數據,在使用partial時,也需要指定。ex:
1: exports.index = function(req, res){
2: Post.get(null, function(err, posts) {
3: if (err) {
4: posts = [];
5: }
6: res.render('index', {
7: title: '首頁',
8: posts : posts,
9: user : req.session.user,
10: success : req.flash('success').toString(),
11: error : req.flash('error').toString()
12: });
13: });
14: };
需要在render時傳入相應的數據{user:xx, error:xx}
index.ejs中如果需要載入其它ejs文件(例如同級目錄下的posts.ejs文件)
1: <%- partial('posts', {posts:posts}) %>
如果不傳入{posts:posts}的話,posts.ejs在使用posts會報錯。
6、在使用mongodb來存儲sessions時,你需要先安裝MongoDB。如果安裝MongoDB?,請參考這里>>
最后來張實際運行的效果圖:
本示例用到的nodejs、MongoDB還有express等文件,已全部打包到一個文件中,有興趣的同學可以從這里進行下載>>
如果對本實例有任何疑問或者有興趣與我進行交流、討論,可以使用E-mail與我聯系(email地址詳見blog左上角),不保證立即回復,敬請諒解:)