路由是最能体现一个网站运作方式的文件,然而如果里面放入太多方法,就会变得臃肿,所以将方法放入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;
路由优化与控制器分离
本文介绍了如何通过将路由方法从Express应用中分离到独立的控制器文件来提高代码的可读性和可维护性。通过示例展示了优化前后路由处理的变化,使得代码结构更加清晰。
4519

被折叠的 条评论
为什么被折叠?



