Express 自动路由加载模块
npm i express-load-router -S
const path = require('path');
const express = require('express');
const loadRouter = require('express-load-router');
const app = express();
// Use `path.join(__dirname, 'path/to/folder')` here
loadRouter(app, path.join(__dirname, 'controllers'));
loadRouter(app, path.join(__dirname, 'controllers'), options);
选项 | 类型 | 默认值 |
---|---|---|
excludeRules |
Array | [] |
rewriteRules |
Map | new Map() |
使用此模块的时候,有三种 Controller
的声明方式:
- 函数
exports.api = (req, res) => {
res.send('API');
};
- 对象
属性 | 类型 | 是否必须 | 默认 | 备注 |
---|---|---|---|---|
method | String | No | GET |
枚举值 ['GET', 'POST', 'PUT', 'DELETE'] |
params | Array | No | [] |
|
middlewares | Array | No | [] |
中间件数组,详见下方文档 |
handler | Function | Yes | -- |
e.g.
exports.api = {
method: 'GET',
params: [':id'],
handler(req, res) {
res.send('API');
}
};
模块支持在 controller
中使用 middlewares
e.g.
exports.api = {
method: 'GET',
params: [':id'],
middlewares: [
function (req, res, next) {
console.log('Middleware 1');
next();
},
function (req, res, next) {
console.log('Middleware 2');
next();
},
],
handler(req, res) {
return res.send(`product detail ${req.params.id}`);
},
};
见 example.
The MIT License