這段時間一直研究express的源碼,有點看不下去了,索性就寫一個用express實現(xiàn)MVC框架的例子。
源碼位置
MVC框架介紹
這里英文大多是摘抄的,別介意哈
This pattern is great for separating the responsibility of the different parts of app and makes your code easier to maintain
- M is for model. A place to define data structures and methods to interact with your data store.
- V is for view. A place to manage everything the end user sees on his or her screen.
- C is for controller. A place to take user requests, bring data from the model and pass it back to the view.
Model是定義數(shù)據(jù)結(jié)構(gòu)和方法,并且和數(shù)據(jù)庫進行交互。
View是用數(shù)據(jù)渲染用戶看到的視圖顶别。
Controller是處理用戶請求,從Model中拿到數(shù)據(jù)給到view視圖谷徙。
不bb了,上代碼
app.js是應用程序的開啟點,以下是app.js
var express = require('express');
var app = express();
var bodyParse = require('body-parser');
var config = require('./config');
var port = process.env.PORT || 3000;
var db = require('./db');
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use('/public', express.static(__dirname + '/public'));
app.use(bodyParse.json());
app.use(bodyParse.urlencoded({extended: true}));
app.use(require('./controllers'));
db.connect(config.db);
app.listen(port, function() {
console.log('listen to port:' + port);
})
24行的通過require('express')獲取的
express
,實際上require('express')
的返回值是個工廠函數(shù),用于生產(chǎn)應用程序。25行通過app()調(diào)用獲取了一個應用程序?qū)嵗?相當于new一個應用程序?qū)嵗?驯绎。
26,27行分別引入依賴和外部文件完慧。
-
29,31行分別定義端口和引入外部文件。
- 如果直接運行
node app.js
,Node 會使用 3000 端口; - 如果
PORT=4444 node index.js
,Node會監(jiān)聽4444端口
- 如果直接運行
33行告訴express我們這次把模板放到
views
目錄下面剩失。34行告訴express我們這次使用的jade模板屈尼。
36行是express托管靜態(tài)文件,只要請求路徑為
\public
的,就進'public'文件夾。38,39行是把請求參數(shù)解析到
req.body
屬性上拴孤。-
40行是加載
controllers
文件夾,實際引入的是controllers
下的index.js
fileThis is the folder where you will be defining all the routes that your app will serve. Your controllers will handle web requests, serve your templates to the user and interact with your models to process and retrieve data. It’s the glue which connects and controls your web app.
以上是介紹
controllers
文件夾的,總結(jié)起來:在controllers
中定義router(路由)服務器啟動后,路由就被加載進來了,路由中只要有
comments
,就走comments
的處理邏輯,其他依然脾歧。 42行是連接數(shù)據(jù)庫,一旦程序啟動時調(diào)用
require('mongoose')
后,后面每次調(diào)用require('mongoose')
后,獲得的是第一次加載的mongoose
對象。這里的原因是:module caching演熟。44行監(jiān)聽特定端口,但是要大于
1024
鞭执。
下面是controller
代碼
var express = require('express');
var router = express.Router();
router.use('/comments', require('./comments'));
router.use('/users', require('./users'));
router.get('/', function(req, res){
res.render('index');
});
module.exports = router;
69行:通過
express.Router()
創(chuàng)建一個路由器對象,可以看作一個獨立的mini app,它也可以調(diào)用use方法加入中間件,但只作用于自身。87,88,89行:相應的路由,走相應的處理邏輯绽媒。
以請求路徑為/comments/all
為例:
在index中匹配到
router.use('/comments', require('./comments'));
而在
comments
file中匹配到下面的路由,從而調(diào)用下面的邏輯蚕冬。
router.get('/all', function(req, res){
Comment.userList(function(err, docs) {
res.render('comments', {comments: docs});
});
});
而數(shù)據(jù)的獲取怎么少得了model
層呢,下面是model
層的代碼。
var mongoose = require('mongoose');
var schema = mongoose.Schema;
var CommentSchema = schema({
name: {type:String, required:true},
remark: { type:String }
});
CommentSchema.statics.userList = function(cb) {
Comment.find().limit(20).exec(function(err, users) {
if (err) return cb(err);
return cb(null, users);
})
}
var Comment = module.exports = mongoose.model('comment', CommentSchema);
model層定義數(shù)據(jù)結(jié)構(gòu)和方法,并且把方法暴露出去,方便調(diào)用,比較簡單是辕。
controller層獲取數(shù)據(jù)后,調(diào)用res.render('comments', {comments: docs});
進行渲染數(shù)據(jù)囤热。
返回給客戶端,完成整個請求获三。