controller,使路由变得简介
路由是最能体现一个网站运作方式的文件,然而如果里面放入太多方法,就会变得臃肿,所以将方法放入controller(控制器)。
下面看一下对比:
方法放入controller前:
module.exports = function (app) { app.get('/pages/main_page.html', function (req, res) { res.sendfile('public/pages/main_page.html'); }); app.post('/pages/save_meal_info',function(req,res){ var lists = new List_info(req.body.name,req.body.restaurant,req.body.meal,req.body.price); lists.save(function(err){ }) }); app.get('/pages/get_meal_list',function(req,res){ Take_list.getAll(function (err, posts) { if (err) { posts=[] } res.send(posts) }) }); app.get('/pages/order-meal.html', function (req, res) { res.sendfile('public/pages/order-meal.html'); }); app.get('/pages/pick_people.html', function (req, res) { res.sendfile('public/pages/pick_people.html'); }); app.get('/pages/get_names',function(req,res) { Person.getAll() .then(function(result){ res.send(result) }) });
放入controller后:
module.exports = function (app) { app.get('/pages/get_names', NameController.getAll); app.get('/pages/get_meal_list', OrderFormController.getAll); app.get('/pages/main_page', MainControllre.show); app.post('/pages/save_meal_info', OrderFormController.save); app.get('/pages/order-meal', OrderMealController.show); app.get('/pages/pick_people', PickPeopleController);
整洁,一目了然。
写法:
在根目录新建文件夹controller用于存放,最好操作同一数据的controller放在一个文件中。
controller示例:
function ListInfoController(){ } ListInfoController.show = function(req,res){ res.sendfile('public/pages/show_list.html'); }; module.exports = ListInfoController;
Person = require('../models/Person.js'); function NameController(){ } NameController.getAll = function(req,res){ Person.getAll() .then(function(name){ res.send(name) }) }; module.exports = NameController;
相关推荐
liuxudong00 2020-11-19
wwzaqw 2020-11-11
lihaoxiang 2020-11-05
CrossingX 2020-11-04
xuegangic 2020-10-17
86417413 2020-11-25
83206733 2020-11-19
86276537 2020-11-19
83266337 2020-11-19
86256434 2020-11-17
zhouboxiao 2020-11-16
rise 2020-11-22
sssdssxss 2020-11-20
windle 2020-11-10
孙雪峰 2020-10-30
85477104 2020-11-17
xfcyhades 2020-11-20
cheidou 2020-11-19