# kk mock server **Repository Path**: bugeiguojiatuohoutui/kk-mock-server ## Basic Information - **Project Name**: kk mock server - **Description**: 一个操作简易、规则可配的 mock server - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 2 - **Forks**: 0 - **Created**: 2024-11-15 - **Last Updated**: 2025-08-11 ## Categories & Tags **Categories**: Uncategorized **Tags**: Mock, mock-server, json-server ## README # kk Mock Server 这是一个基于 `json-server` 的 RESTful API 服务器,用于模拟后端接口服务。它包含了自定义中间件来处理跨域请求、认证以及日志记录等功能。 ## 特性 - **RESTful API**: 使用 `json-server` 快速创建 RESTful API。 - **跨域支持**: 可选的自定义中间件处理跨域请求。 - **认证机制**: 可选的 Bearer Token 认证。 - **日志记录**: 使用 `json-server` 自带记录 HTTP 请求日志功能。 - **命令行参数**: 支持通过命令行参数配置端口、API 路径前缀、允许的跨域来源和认证 token。 - **动态数据**: 使用 `faker` 生成模拟数据,还可以根据模拟的数据更新(模拟请求时,增加、删除数据文件)。 ## 安装 首先,确保已经安装了 Node.js 和 npm。然后,克隆仓库并安装依赖: ```bash git clone https://gitee.com/bugeiguojiatuohoutui/kk-mock-server.git cd mock-server npm install ``` ## 使用 ### 启动服务器 运行以下命令启动服务器: ```bash npm start # or npm run serve ``` 这将启动服务器,监听端口 5432,API 路径前缀为 `api/v1`,没有跨域限制,不需要 auth 认证。 ### 命令行参数 | 参数 | 简写 | 描述 | 类型 | 默认值 | | ------------------ | ---- | ---------------------------- | ------ | -------- | | `--port` | `-p` | 服务启动的端口号 | number | `5432` | | `--apiPath` | `-a` | API 路径前缀 | string | `api/v1` | | `--allowedOrigins` | `-o` | 允许的跨域来源,逗号分隔 | string | 无 | | `--auth` | `-u` | 是否开启认证,以及认证 token | string | 无 | 参数配置通过 meow 这个 npm 包实现的。 所有参数都是可选的,如果不传入参数,将按照默认参数值启动服务。 #### --port 配置服务启动的端口号,如果没配置,会启动:http://localhost:5432 #### --apiPath 排除 origin 后的路径,为了平台兼容性,其值不能 '/' 开头 #### --allowedOrigins 允许访问的源列表,为避免兼容问题,这个参数值加引号: - 空,允许所有源访问 - `'*'`,允许所有源访问 - `'true'`,允许所有源访问 - '`false'`,禁止所有源访问 - `'http:localhost:123'`,只允许 http:localhost:123 访问 - `'http:localhost:123,http:localhost:456'`,允许这两个源访问,注意逗号分隔,**逗号后面没有空格**。 #### --auth 这只是一个简单头部的字符串校验,不涉及 token 密钥生成,会拼接为:`Bearer ${auth}`,所以传参时 `Bearer ` 不用传递。 #### 举例: 举例1,如果启动服务器并配置端口为 3000,API 路径前缀为 `api/v2`,允许来自 `http://localhost:3000` 和 `http://localhost:8080` 的跨域请求,启用认证并使用 `my-secret-token` 作为认证 token,那么命令为: ```bash npm run serve -- -p 3000 -a api/v2 -o http://localhost:3000,http://localhost:8080 -u my-secret-token ``` 举例2,无跨域限制启动服务: ```shell npm start -- -o '*' ``` `--` 后面的参数会替换掉 meow 中配置的默认参数。 参数 key 是 `-` 开头简写或 `--` 开头完整 key name,value 不能 `/` 开头。 整体参数以:`key1 value1 key2 value key3 value` 的格式传入。也就是,参数名和对应的值用空格分隔,多个参数对彼此也是空格分隔。 ## 客户端请求示例 如果用 Postman,相关 API 已经导出,可直接导入 ‘json-server 5432.postman_collection.json’ 使用。 ### 创建一个新用户(使用 POST 请求) ```js fetch('http://127.0.0.1:5432/api/v1/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: 'newuser', email: 'newuser@example.com' avatar:'aa.jpg', password:'aaaaa3333' }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` 如果是 Postman ![image-20231219133224914](http://img.zhangzhenkun.com/image-20231219133224914.png) ![image-20231219130151098](http://img.zhangzhenkun.com/image-20231219130151098.png) 如果没在 Postman 统一设置头,则需要把认证加上: ![image-20231219130115892](http://img.zhangzhenkun.com/image-20231219130115892.png) ### 获取用户列表(使用 GET 请求) ```js fetch('http://127.0.0.1:5432/api/v1/users') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` ### 更新用户信息(使用 PUT 请求) ```js fetch('http://127.0.0.1:5432/api/v1/users/1', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id:1, username: 'updateduser', email: 'updateduser@example.com' }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` ### 删除一个用户(使用 DELETE 请求) ```js fetch('http://127.0.0.1:5432/api/v1/users/1', { method: 'DELETE' }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` ## 默认 db.json API 参考 ### 用户 (Users) #### 1. 获取所有用户 (查询方法) - **方法**: `GET` - **URL**: `/api/v1/users` - **参数**: 无 - **返回值**: `json` (包含所有用户的数组) #### 2. 创建新用户 (创建方法) - **方法**: `POST` - **URL**: `/api/v1/users` - **参数**: - `username` (string): 用户名 - `email` (string): 电子邮件 - `avatar` (string): 头像 URL - `password` (string): 密码 - **返回值**: `json` (新创建的用户对象) #### 3. 获取特定用户 (查询方法) - **方法**: `GET` - **URL**: `/api/v1/users/{userId}` - **参数**: - `userId` (integer): 用户ID - **返回值**: `json` (包含特定用户信息的对象) #### 4. 更新用户信息 (更新方法) - **方法**: `PUT` - **URL**: `/api/v1/users/{userId}` - **参数**: - `username` (string): 用户名 - `email` (string): 电子邮件 - `avatar` (string): 头像 URL - `password` (string): 密码 - **返回值**: `json` (更新后的用户对象) #### 5. 删除用户 (删除方法) - **方法**: `DELETE` - **URL**: `/api/v1/users/{userId}` - **参数**: - `userId` (integer): 用户ID - **返回值**: `json` (空对象) ### 帖子/文章 (Posts) #### 1. 获取所有帖子 (查询方法) - **方法**: `GET` - **URL**: `/api/v1/posts` - **参数**: 无 - **返回值**: `json` (包含所有帖子的数组) #### 2. 创建新帖子 (创建方法) - **方法**: `POST` - **URL**: `/api/v1/posts` - **参数**: - `title` (string): 帖子标题 - `content` (string): 帖子内容 - `userId` (integer): 发布帖子的用户ID - **返回值**: `json` (新创建的帖子对象) #### 3. 获取特定帖子 (查询方法) - **方法**: `GET` - **URL**: `/api/v1/posts/{postId}` - **参数** - `postId` (integer): 帖子ID - **返回值**: `json` (包含特定帖子信息的对象) #### 4. 更新帖子信息 (更新方法) - **方法**: `PUT` - **URL**: `/api/v1/posts/{postId}` - **参数**: - `title` (string): 帖子标题 - `content` (string): 帖子内容 - `userId` (integer): 发布帖子的用户ID - **返回值**: `json` (更新后的帖子对象) #### 5. 删除帖子 (删除方法) - **方法**: `DELETE` - **URL**: `/api/v1/posts/{postId}` - **参数**: - `postId` (integer): 帖子ID - **返回值**: `json` (空对象) ### 评论 (Comments) #### 1. 获取所有评论 (查询方法) - **方法**: `GET` - **URL**: `/api/v1/comments` - **参数**: 无 - **返回值**: `json` (包含所有评论的数组) #### 2. 创建新评论 (创建方法) - **方法**: `POST` - **URL**: `/api/v1/comments` - **参数**: - `text` (string): 评论内容 - `userId` (integer): 发表评论的用户ID - `postId` (integer): 评论所属的帖子ID - **返回值**: `json` (新创建的评论对象) #### 3. 获取特定评论 (查询方法) - **方法**: `GET` - **URL**: `/api/v1/comments/{commentId}` - **参数**: - 无 - **返回值**: `json` (包含特定评论信息的对象) #### 4. 更新评论信息 (更新方法) - **方法**: `PUT` - **URL**: `/api/v1/comments/{commentId}` - **参数**: - `text` (string): 评论内容 - `userId` (integer): 发表评论的用户ID - `postId` (integer): 评论所属的帖子ID - **返回值**: `json` (更新后的评论对象) #### 5. 删除评论 (删除方法) - **方法**: `DELETE` - **URL**: `/api/v1/comments/{commentId}` - **参数**: - 无 - **返回值**: `json` (空对象) ## db.json 说明 db.json 是通过 createData.js 生成的模拟数据库。 如果要扩展数据或修改数据格式,需要修改 fakerFunctions.js,并在 createData.js 中引入。fakerFunctions 参考 faker 官方文档 https://fakerjs.dev/。 ## 日志记录 服务器使用 `json-server` 自带的记录 HTTP 请求日志,客户端发送一次请求,可在控制台看出请求方法、路径、状态码。 ```shell $ npm start -- -p 123 -a api -o http://localhost:3000,http://localhost:3333 -u zzk > kk-mock-server@3.1.1 start > node server.js -p 123 -a api -o http://localhost:3000,http://localhost:3333 -u zzk 服务已启动... 允许的跨域源:http://localhost:3000,http://localhost:3333 启用认证,认证 token 是:Bearer zzk 本 地 URL 是:http://localhost:123/api 局域网 URL 是:http://10.31.3.62:123/api GET /api/users 200 34.636 ms - 402 ``` 这最后一行就是日志 ## 项目结构 ``` . ├── db.json # 数据源文件 |—— createData.js # 重新生成 db.json ├── server.js # 服务器入口文件 ├── package.json # 项目配置文件 └── README.md # 项目文档 ``` ## 帮助 meow 生成的帮助。 ```shell npm run help ``` ```shell Administrator@DESKTOP-N2LTLL4 MINGW64 /d/works/mock-server (master) $ npm run help > kk-mock-server@3.1.1 help > node server.js --help 使用方式: $ npm run serve -- --port 5432 --apiPath api/v1 --allowedOrigins "http://localhost:5173,http://localhost:3000" --auth "your-token" 参数: --port, -p 监听的端口号,默认值:5432 --apiPath, -a API 路径前缀,不能用 '/' 作为前缀,默认值: api/v1 --allowedOrigins, -o 允许的跨域来源,逗号分隔,默认值:无 --auth, -u 认证 token,默认值:无 ``` ## 贡献 欢迎贡献!请遵循 [贡献指南](CONTRIBUTING.md)。 ## 许可 本项目采用 MIT 许可证。 ## 更新日志: v3.3.2:2024-11-19,用 cors 包处理跨域,更改 auth 认证逻辑,让 get 请求也需要 auth 认证。 v3.1.1:2024-11-15,更改跨域规则,默认允许所有源,传入特定源或源列表,则只允许传入源跨域。 v3.0.3:2024-11-14,如果端口被占用,尝试端口 +1 后启动。 v3.0.1:2024-06-20,用 meow 配置 CLI,参数不用修改代码,而是可以从命令行传入,主代码用 mjs 重新引用。 v2.2.4:2023-11-08,全部重写,引入 json-server,支持中间件方式配置路由、跨域。引入 faker.js,支持数据库生成。 ## 联系 如果有任何问题或建议,请联系 2202084770@qq.com。