Skip to content

Latest commit

 

History

History
119 lines (90 loc) · 2.55 KB

README.zh_CN.md

File metadata and controls

119 lines (90 loc) · 2.55 KB

express-load-router

Express 自动路由加载模块

NPM version npm download David deps

安装

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 声明方式

使用此模块的时候,有三种 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