express-autoload-router
模塊用於自動加載並註冊路由。node
基本使用步驟以下。git
$ npm install express-autoload-router
將路由程序文件放在專門的目錄app/controllers
下面。格式上有兩點須要注意:github
xxx_controller.js
;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()
函數的第二個參數指定一級路由,第二個參數指定路由程序文件所在的目錄。express
該函數會調用app.METHOD()
(METHOD在這裏替換爲get、post等HTTP方法)註冊相應的路由,路由URI爲:/demo/xxx/yyy
。npm
$ curl -X GET http://localhost:3000/demo/user/list user list action
路由程序文件中的yyyAction
能夠寫成函數,也能夠寫成對象,二者是等價的。app
基本寫法以下:curl
// 普通路由,訪問方式:/demo/product/list module.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"); };
函數再簡化一點:post
// 更簡化函數:function 改爲 =>,省略大括號 // URL使用大小寫都可:/demo/product/moreSimple 或 /demo/product/moresimple exports.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/product module.exports.indexAction = function(req, res) { return res.send("product index action"); }; // 普通路由,訪問方式:/demo/product/list module.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/subdir module.exports.listAction = function(req, res) { return res.send("subdir/subroute list action"); };
listAction
對應的路由爲/demo/subdir/subroute/list
。因而可知,子目錄有會做爲路由的一部分。