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;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值