MVC即 model 、controller、view;
M: Model 数据模型层
V: View 视图层
C: Controller 逻辑控制层
MVC模式将model、view、controller分离;
使用mvc分层是系统更加灵活,扩展性更强。让程序更加直观、复用性更强、可维护性更强。
model 负责数据访问;
controller 负责消息处理;
view 负责视图呈现;
简易封装一个MVC的方法:
index.js文件:
- var http=require("http")
- var router =require("./router.js")
- var controller =require("./controller.js")
- var app=http.createServer(router)
- //静态资源托管
- router.static(__dirname+"/src")
- //注册网址
- router.get("/ajax1",controller.ajax1)
- router.get("/ajax2",controller.ajax2)
- router.get("/ajax3",controller.fn)
-
- app.listen(8081)
router.js文件:
- var fs = require("fs")
- var url = require("url")
- var querysting = require("querystring")
- var mime = require("mime")
- let urls = {}
- let router = function (req, res) {
- //这个函数每次用户访问时运行
- let pathname = url.parse(req.url).pathname
- fs.readFile(router.basepath + pathname, (err, data) => {
- if (!err) {
- res.setHeader("content-Type", mime.getType(pathname))
- res.end(data)
- } else {
- if (!urls[pathname]) {
- res.end("404 not found")
- } else {
- urls[pathname](req, res)
- }
- }
- })
- }
- router.static = function (path) {
- this.basepath = path
- }
- router.get = function (url, cb) {
- urls[url] = cb
- }
- router.basepath = __dirname + "/src"
- module.exports = router;
controller.js文件:
- module.exports = {
- ajax1(req, res) {
- // 业务代码
- },
- ajax2() {
- // 业务代码
- },
- fn() {
- // 业务代码
- }
- }