api-proxy-mock/README.md
2026-03-13 14:36:26 +08:00

88 lines
2.8 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## API Proxy Mock
一个基于 Node.js 的轻量级 **HTTP 代理 + 本地 Mock** 服务,通过配置文件 `config.json` 控制要拦截的路由及其返回数据。
### 功能说明
- **代理转发**:非 Mock 路由会被转发到真实后端(`config.config.targetHost`)。
- **本地 Mock**:在 `config.json` 中配置的路由会直接从本地 `mock` 目录读取文件并返回。
- **热更新配置**
- `config.config.reloadOnChange = true` 时,监控 `config.json` 文件变化,自动重新加载配置。
- 也可以通过管理接口手动触发重新加载。
### 配置文件 `config.json`
基础结构:
```json
{
"routes": {
"/api2/example": "mock/example.txt"
},
"config": {
"cacheConfig": true,
"reloadOnChange": true,
"defaultContentType": "application/json",
"proxyPort": 9443,
"targetHost": "devrmtapp.resmart.cn"
}
}
```
- **`routes` 部分**
- key请求路径只匹配 `pathname`,不含域名和查询参数),例如:`"/api2/test"`
- value相对 `index.api.ts` 所在目录的本地文件路径,例如:`"mock/test.txt"`
- **重要:以 `#` 开头的路由 key 会被视为注释,不参与 Mock 拦截**
- 例:
```json
{
"routes": {
"#/api2/test": "mock/test.txt",
"/api2/real": "mock/real.txt"
}
}
```
上例中,`#/api2/test` 会被当作注释忽略,只有 `/api2/real` 会真的被 Mock。
- **`config` 部分**
- `cacheConfig`: 是否使用内存缓存配置(当前主要用于记录上次加载结果)。
- `reloadOnChange`: 是否监控 `config.json` 变化并自动重新加载。
- `defaultContentType`: Mock 响应默认的 `Content-Type`,例如 `"application/json"`。
- `proxyPort`: 本地代理服务器监听的端口,例如 `9443`。
- `targetHost`: 转发真实请求时的目标后端域名,例如 `"devrmtapp.resmart.cn"`。
### 启动项目
1. 确保安装 Node.js建议 18+)。
2. 在项目根目录安装依赖(目前只使用 Node 内置模块,`@types/node` 为开发辅助类型):
```bash
npm install
```
3. 使用 `ts-node` 或先编译再运行:
- 直接运行(推荐开发环境):
```bash
npx ts-node index.api.ts
```
- 或者如果你使用普通 Node 运行,先把文件编译/改为 JS 再执行:
```bash
node index.api.js
```
启动成功后,控制台会输出类似信息:
```text
代理服务器运行在: http://localhost:<proxyPort>
目标服务器: https://<targetHost>
配置文件: <config.json 的路径>
```
### 管理接口
- 查看当前配置:
- `GET http://localhost:<proxyPort>/__config`
- 手动重新加载配置:
- `POST http://localhost:<proxyPort>/__reload-config`
其中 `<proxyPort>` 取自 `config.config.proxyPort`。