模块介绍
express-autoload-router
模块用于自动加载并注册路由。
模块使用
基本用法
基本使用步骤如下。
安装模块
$ npm install express-autoload-router
构建路由程序
将路由程序文件放在专门的目录app/controllers
下面。格式上有两点需要注意:
- 路由程序文件名称必须为
xxx_controller.js
; - 路由程序中的action函数/对象名称必须为
yyyAction
;
$ cat app/controllers/user_controller.js
/** * 对象方式,多个路由放在一起 */module.exports = { listAction: { method: ["GET"], middlewares: [], handler: function(req, res) { return res.send("user list action"); } }, getAction: { method: ["GET"], middlewares: [], handler: function(req, res) { return res.send("user get action"); } }};
在主程序中引入并加载路由
$ cat app.js
const express = require("express");const path = require('path');const loadRouter = require('express-autoload-router');const app = express();loadRouter(app, "/demo", path.join(__dirname, "app/controllers"));app.listen(3000, function() { console.log("Listening on port 3000!");});
其中,loadRouter()
函数的第二个参数指定一级路由,第二个参数指定路由程序文件所在的目录。
该函数会调用app.METHOD()
(METHOD在这里替换为get、post等HTTP方法)注册相应的路由,路由URI为:/demo/xxx/yyy
。
使用示例
$ curl -X GET http://localhost:3000/demo/user/listuser list action
路由程序文件的写法
路由程序文件中的yyyAction
可以写成函数,也可以写成对象,两者是等价的。
使用函数
基本写法如下:
// 普通路由,访问方式:/demo/product/listmodule.exports.listAction = function(req, res) { return res.send("product list action");};
由于在node.js
当中,module.exports
和exports
等价,所以也可以写成:
// module.exports和exports等价exports.getAction = function(req, res) { return res.send("product get action");}
另外,函数也可以简化:
// 简化函数:function 改成 =>exports.simpleAction = (req, res) => { return res.send("product simple action");};
函数再简化一点:
// 更简化函数:function 改成 =>,省略大括号// URL使用大小写均可:/demo/product/moreSimple 或 /demo/product/moresimpleexports.moreSimpleAction = (req, res) => res.send("product moreSimple action");
使用对象
基本写法:
module.exports.buyAction = { method: ["GET", "POST"], middlewares: [], handler: function(req, res) { return res.send("product buy action"); }};
等价写法:
// handler的另一种写法exports.sellAction = { method: ["GET", "POST"], middlewares: [], handler(req, res) { return res.send("product sell action"); }};
注意事项
indexAction
的处理
indexAction
中的index
不会作为组成路由的一部分。比如,对于路由文件product_controller.js
,有:
// 默认路由,访问方式:/demo/productmodule.exports.indexAction = function(req, res) { return res.send("product index action");};// 普通路由,访问方式:/demo/product/listmodule.exports.listAction = function(req, res) { return res.send("product list action");};
其中,listAction
对应的路由为/demo/product/list
,而indexAction
对应的路由为/demo/product
。
路由子目录(子路由)
假设controllers
目录下有一个子目录subdir
,其中有一个路由程序文件subroute_controller.js
,如下:
$ cat app/controllers/subdirmodule.exports.listAction = function(req, res) { return res.send("subdir/subroute list action");};
listAction
对应的路由为/demo/subdir/subroute/list
。由此可见,子目录有会作为路由的一部分。
源码分析
参考资料
- express-autoload-router 模块源码
- 本文源码