api-proxy-mock/README.md
2026-04-07 23:37:22 +08:00

108 lines
3.6 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` 里配置要拦截的路径和本地文件,其余请求通过 **HTTPS** 转发到真实后端。
### 功能说明
- **代理转发**:未命中 Mock 的请求会转发到 `config.targetHost`HTTPS`targetPort` 可配,默认 443
- **本地 Mock**:命中路由时直接读取 `mock` 目录下的文件作为响应体。
- **Mock 总开关**`mockEnabled``false` 时**不拦截**任何 Mock 路由,全部走代理。
- **热更新**`reloadOnChange``true` 时监听 `config.json` 变更并自动重载;也可通过管理接口手动重载。
- **Mock 响应**:带简单 CORS 头,以及 `X-Mock-Source``X-Mock-Timestamp` 便于排查。
### 环境要求
- Node.js建议 18+
- 依赖见 `package.json``typescript``ts-node``@types/node`(仅开发/类型)
### 安装与启动
```bash
npm install
```
推荐使用 npm 脚本(使用项目内 `tsconfig.json`,避免 `tsc .\某文件.ts` 触发 TS5112
```bash
npm run dev
# 或
npm start
```
等价于:
```bash
npx ts-node --project tsconfig.json ./index.api.ts
```
类型检查(不生成 JS
```bash
npm run typecheck
```
启动成功后,控制台会输出本地监听地址、目标主机与配置文件路径等。
### 配置文件 `config.json`
`index.api.ts` 同目录。若首次运行不存在,程序会生成一份默认配置。
基础结构示例:
```json
{
"routes": {
"/api/example": "mock/example.txt"
},
"config": {
"mockEnabled": true,
"cacheConfig": true,
"reloadOnChange": true,
"defaultContentType": "application/json",
"proxyPort": 8877,
"targetHost": "example.com",
"targetPort": 443
}
}
```
#### `routes`
| 说明 | |
| --- | --- |
| **key** | 请求路径,只匹配 **pathname**(不含域名;查询串不参与匹配),例如 `"/api/user/info"`。 |
| **value** | 相对项目根目录(与 `index.api.ts` 同级)的文件路径,例如 `"mock/user.txt"`。 |
| **注释** | 以 **`#`** 开头的 key 视为注释,**不参与** Mock。例如 `"#/api/old": "mock/x.txt"` 会被忽略。 |
#### `config`
| 字段 | 说明 |
| --- | --- |
| `mockEnabled` | 可选。为 `false` 时关闭 Mock所有请求走代理缺省为 `true`。 |
| `cacheConfig` | 保留字段;当前实现中未参与逻辑,可忽略或与旧配置兼容。 |
| `reloadOnChange` | 是否监视 `config.json` 文件变化并自动重新加载。 |
| `defaultContentType` | Mock 成功时的 `Content-Type`,常用 `"application/json"`。 |
| `proxyPort` | 本机 HTTP 代理监听端口。 |
| `targetHost` | 上游 HTTPS 主机名(不含协议与路径)。 |
| `targetPort` | 可选。上游 HTTPS 端口,**缺省为 443**。非 443 时请在配置中显式写出。 |
### 管理接口
`<proxyPort>` 换为 `config.proxyPort` 中的值:
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| `GET` | `http://localhost:<proxyPort>/__config` | 查看当前路由与配置 |
| `POST` | `http://localhost:<proxyPort>/__reload-config` | 手动重新加载 `config.json` |
### TypeScript 与编译说明
- 项目根目录包含 `tsconfig.json`,请使用 **`tsc -p .`** 或 **`npm run typecheck`** 做整项目检查。
- **不要**使用 `tsc .\index.api.ts` 这类「命令行附带单个文件」的方式,否则会与 `tsconfig.json` 冲突并报 **TS5112**
### 目录说明
- `index.api.ts`:服务入口。
- `config.json`:路由与运行参数。
- `mock/`Mock 响应文件(文本内容原样返回,按需自行写成 JSON 等)。