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,使路由变得简介

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;

相关推荐