前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >express的路由配置优化

express的路由配置优化

作者头像
meteoric
发布2018-11-19 16:27:45
1.2K0
发布2018-11-19 16:27:45
举报
文章被收录于专栏:游戏杂谈游戏杂谈

默认情况下,express的路由写起来还挺麻烦的。比如下面这样:

app.get('/blacklists/', get_all); app.get('/blacklists/:id', get_all); app.post('/blacklists/:id', update); app.post('/blacklists', create); app.detete('/blacklists/:id' : del);

这样写是什么大的问题,至少它能正常运行。但有二个小问题:

1、不便于以后的扩展和维护,如果需要监听的URL越来越多,它看上去就会越来越糟糕了;

2、不够灵活,如果还需要对“hello”、“aa”…进行监听,所有的代码处理都被放在一个地方了,只会越来越臃肿;

有没有比较好的方案对路由的处理管理和配置呢?

我们可以使用“惯例优先原则”来定义好一个约定:我期望的是所有的路由相关的处理,都放在项目文件路径下,一个名为“routes”的文件夹里,里面可以可以再建立N层文件夹,而每一个js文件,仅处理以该文件名为路径的请求,如上面的“blacklists”相关的处理全部放在blacklists.js文件内。如何实现呢?

1、获取当前项目routes目录内所有的文件(包含子文件夹);

2、加载每一个文件,获取指定属性下的配置,如果存在,就动态拼接成如文章开头的配置,如:app[method](path, func);

部分实现代码:

代码语言:javascript
复制
//假设文件存放在routes目录,取名为hello.js
exports.autoroute = {
    'get' : {
        '/hello(/?)' : hello,
        '/hello/:id' : hello2
    },
    'post' : {

    }
}

function hello(req, res) {
    res.end('hello');
}

function hello2(req, res) {
    res.end('hello ' + req.params.id);
}
------------------------------------------------------------------------
//当前项目的routes目录的路径
var routesDir = path.dirname(require.main.filename) + "/routes";

fs.readdir(routesDir, function(err, files) {
    if (err) {
        return ;
    }

    files.forEach(function(path) {
        //routes目录下的文件路径
        var filePath = routesDir + "/" + path;
        
        fs.stat(filePath, function(err, stats) {
            if (err) {
                return ;    
            }

            if (stats.isDirectory()) {
                //递归执行函数
            } else  {
                //加载文件并解析
                    loadFile(filePath);
            }
        })
    });
})


function loadFile(filePath) {
    var routeObj = require(filePath);
    
    //如果包含autoroute属性,则进行解析
    if (routeObj.autoroute) {
        /*
         * autoroute就是上面hello.js的内容:
            'get' : {
               '/hello(/?)' : hello,
               '/hello/:id' : hello2
           },
           'post' : {
        
           }
         */
        for (var method in routeObj.autoroute) {
            var routeList = routeObj.autoroute[method];
            
            if (!routeList) {
                break ;
            }
            
            //method就是上面取到的get、post

            for(var routeRule in routeList) {
                //func获取得到的就是上面对应各项的处理函数
                var func = routeList[path];

                app[method](routeRule, func);
            }
        }
    }
}

运行后的效果如下:

如果routes有同名的两个js文件,分属于不同的文件夹,那会是怎么样的结果呢?假设dd目录下也有相同的一个js文件hello.js

代码语言:javascript
复制
exports.autoroute = {
    'get' : {
        '/hello(/?)' : hello,
        '/hello/:id' : hello2
    },
    'post' : {

    }
}

function hello(req, res) {
    res.end('dd hello');
}

function hello2(req, res) {
    res.end('dd hello ' + req.params.id);
}

运行后的效果:

而控制台上也会显示当前监听的url

如此一来,我们的开发就会很方便了。

本文的代码和思路参考了express-autoroute,在express中使用也比较简单^_^

安装:

npm install express-autoroute

使用:

var autorouter = require('express-autoroute');

autorouter(app); //其中app = express();

有兴趣的可以读读它的源码,这篇文章本来就是参数它来的:)

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2013-02-19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档