通過express實現一個簡單的MVC

這段時間一直研究express的源碼,有點看不下去了,索性就寫一個用express實現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是定義數據結構和方法,并且和數據庫進行交互。
View是用數據渲染用戶看到的視圖。
Controller是處理用戶請求,從Model中拿到數據給到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')的返回值是個工廠函數,用于生產應用程序。

  • 25行通過app()調用獲取了一個應用程序實例(相當于new一個應用程序實例)。

  • 26,27行分別引入依賴和外部文件。

  • 29,31行分別定義端口和引入外部文件。

    • 如果直接運行node app.js,Node 會使用 3000 端口;
    • 如果PORT=4444 node index.js,Node會監聽4444端口
  • 33行告訴express我們這次把模板放到views目錄下面。

  • 34行告訴express我們這次使用的jade模板。

  • 36行是express托管靜態文件,只要請求路徑為\public的,就進'public'文件夾。

  • 38,39行是把請求參數解析到req.body屬性上。

  • 40行是加載controllers文件夾,實際引入的是controllers下的index.jsfile

    This 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文件夾的,總結起來:在controllers中定義router(路由)

    服務器啟動后,路由就被加載進來了,路由中只要有comments,就走comments的處理邏輯,其他依然。

  • 42行是連接數據庫,一旦程序啟動時調用require('mongoose')后,后面每次調用require('mongoose')后,獲得的是第一次加載的mongoose對象。這里的原因是:module caching。

  • 44行監聽特定端口,但是要大于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()創建一個路由器對象,可以看作一個獨立的mini app,它也可以調用use方法加入中間件,但只作用于自身。

  • 87,88,89行:相應的路由,走相應的處理邏輯。

以請求路徑為/comments/all為例:

  1. 在index中匹配到router.use('/comments', require('./comments'));

  2. 而在commentsfile中匹配到下面的路由,從而調用下面的邏輯。

router.get('/all', function(req, res){
    Comment.userList(function(err, docs) {
        res.render('comments', {comments: docs});
    }); 
});

而數據的獲取怎么少得了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層定義數據結構和方法,并且把方法暴露出去,方便調用,比較簡單。

controller層獲取數據后,調用res.render('comments', {comments: docs});進行渲染數據。

返回給客戶端,完成整個請求。

應用鏈接

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容