通过express实现一个简单的MVC

2017-07-31  本文已影响0人  踢车牛

这段时间一直研究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

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);
})

下面是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;

以请求路径为/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});进行渲染数据。

返回给客户端,完成整个请求。

应用链接

上一篇下一篇

猜你喜欢

热点阅读