expressautoloadrouter源码分析

5次阅读

共计 2475 个字符,预计需要花费 7 分钟才能阅读完成。

模块介绍

express-autoload-router模块用于自动加载并注册路由。

模块使用

基本用法

基本使用步骤如下。

安装模块

$ npm install express-autoload-router

构建路由程序

将路由程序文件放在专门的目录 app/controllers 下面。格式上有两点需要注意:

  1. 路由程序文件名称必须为xxx_controller.js
  2. 路由程序中的 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/list
user list action

路由程序文件的写法

路由程序文件中的 yyyAction 可以写成函数,也可以写成对象,两者是等价的。

使用函数

基本写法如下:

// 普通路由,访问方式:/demo/product/list
module.exports.listAction = function(req, res) {return res.send("product list action");
};

由于在 node.js 当中,module.exportsexports 等价,所以也可以写成:

// 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/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。由此可见,子目录有会作为路由的一部分。

源码分析

参考资料

  • express-autoload-router 模块源码
  • 本文源码
正文完
 0