mock-service-cli 2.5.1 → 3.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,30 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4
4
 
5
+ ### [3.1.2](https://github.com/chandq/mock-service-cli/compare/v3.1.1...v3.1.2) (2022-08-07)
6
+
7
+ ### [3.1.1](https://github.com/chandq/mock-service-cli/compare/v3.1.0...v3.1.1) (2022-07-25)
8
+
9
+
10
+ ### Bug Fixes
11
+
12
+ * node 18下chalk丢失问题 ([fb80d8d](https://github.com/chandq/mock-service-cli/commit/fb80d8d94feee8d3177b69a2c4509a390880bd56))
13
+ * update some npm version for security ([f0aa1df](https://github.com/chandq/mock-service-cli/commit/f0aa1dfa51f36bde693b0da12bec2b653b1b6003))
14
+
15
+ ## [3.1.0](https://github.com/chandq/mock-service-cli/compare/v3.0.0...v3.1.0) (2022-04-27)
16
+
17
+
18
+ ### Features
19
+
20
+ * **web-proxy:** proxy配置项支持文件和命令行参数字符串两种 ([ee1ce1f](https://github.com/chandq/mock-service-cli/commit/ee1ce1fbefa5ce9b3c074192d2d9893a4414d346))
21
+
22
+ ## [3.0.0](https://github.com/chandq/mock-service-cli/compare/v2.5.1...v3.0.0) (2022-04-27)
23
+
24
+
25
+ ### Features
26
+
27
+ * add web server and request proxy ([e5be340](https://github.com/chandq/mock-service-cli/commit/e5be340940042eb05e2e5cb9d2fcc6f8316052d5))
28
+
5
29
  ### [2.5.1](https://github.com/chandq/mock-service-cli/compare/v2.5.0...v2.5.1) (2022-04-25)
6
30
 
7
31
  ## [2.5.0](https://github.com/chandq/mock-service-cli/compare/v2.4.0...v2.5.0) (2022-04-25)
package/README.md CHANGED
@@ -10,13 +10,32 @@
10
10
 
11
11
  ### 简介
12
12
 
13
- **简易轻量**、**B/S 架构**、**0 秒启动**的本地命令行 Mock 服务套件, 支持热更新,对于开发调试 mock 数据很实用,能提高前端开发者的开发效率。支持 `GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`OPTIONS`,`COPY`,`LINK`,`UNLINK`,`PURGE` 等常用请求类型,无需布署后端,可能是本地最好用的 Mock 工具。支持以下常见业务场景:
13
+ 内置 Mock Server、Web Server、Http request proxy 等功能集。
14
+
15
+ **简易轻量**、**B/S 架构**、**0 秒启动**的本地命令行 Mock 服务套件, 支持热更新,对于开发调试 mock 数据很实用,能提高前端开发者的开发效率。支持 `GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`OPTIONS`,`COPY`,`LINK`,`UNLINK`,`PURGE` 等常用请求类型,无需布署后端,可能是本地最好用的 Mock 工具之一。
16
+
17
+ #### Mock Server - 本地 Mock 服务器
18
+
19
+ 支持以下常见业务场景:
14
20
 
15
21
  - [x] 无服务端演示项目的数据 Mock
16
22
  - [x] 业务开发接口联调前的数据 Mock
17
23
  - [x] 保留业务项目的所有或部分接口的响应数据(写入文件)
18
24
  - [x] 保障前端开发调试不受后端服务影响(当后端服务挂掉或部分接口响应异常时启用 Mock)
19
25
 
26
+ #### Web Server - SPA Web 服务器
27
+
28
+ 对 React、Vue 等单页应用项目构建生成的 dist 目录,启动本地 web 服务器(相当于使用本地安装的 nginx 服务)来模拟运行生产环境下的 web 服务
29
+
30
+ #### Http request proxy - 基于浏览器的本地代理服务
31
+
32
+ 实现了本地接口代理的能力,一般接口测试工具无法查看到 request 和 response 中 headers 的更多详情,这里实现了接口代理功能,在 Network 中可查看接口调用的详细信息。
33
+
34
+ > 两种应用场景
35
+
36
+ - 项目 dev 模式下的接口代理请求
37
+ - Chrome 的 Console 执行 fetch 请求(用于接口测试)
38
+
20
39
  ## Installation:
21
40
 
22
41
  #### Running on-demand:
@@ -45,29 +64,31 @@ This will install `mock-service-cli` globally so that it may be run from the com
45
64
 
46
65
  `[path]` defaults to `./mock` .
47
66
 
48
- | Command | Description | Defaults |
49
- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
50
- | `-h` or `--help` | Print this list and exit. | |
51
- | `-p` or `--port` | Port to use. Use `-p 0` to look for an open port, starting at 8090. It will also read from `process.env.PORT`. | 8090 |
52
- | `-d` | Specify mock directory | ./mock |
53
- | `-f` | Specify mock file | |
54
- | `-s` or `--silent` | Suppress log messages from output | |
55
- | `-v` or `--version` | Print the version and exit. | |
56
- | `-S` or `--socket-server` | Start socket server which used to save api response data for future mock. | false |
57
- | `-a` or `--api-stat` | Whether print api url and file path info or not, default false. | false |
58
- | `-l` or `--log` | Whether record operation info by write file, default false. | false |
59
- | `-o` or `--cors-origin` | Allow origin by cors, list separated by commas, must not be \* when withCredential is true .If specified, cors-headers will be `Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Data-Type,X-Requested-With,X-Data-Type,X-Auth-Token,Token` | \* |
60
- | `-H` or `--cors-headers` | Optionally provide CORS headers list separated by commas | \* |
67
+ | Command | Description | Defaults |
68
+ | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
69
+ | `-h` or `--help` | Print this list and exit. | |
70
+ | `-p` or `--port` | Mock server port to use. Use `-p 8090` to look for an open port, starting at 8090. | 8090 |
71
+ | `-d` | Specify mock directory | ./mock |
72
+ | `-f` | Specify mock file | |
73
+ | `-s` or `--silent` | Suppress log messages from output | |
74
+ | `-v` or `--version` | Print the version and exit. | |
75
+ | `-S` or `--socket-server` | Start socket server which used to save api response data for future mock. | false |
76
+ | `-a` or `--api-stat` | Whether print api url and file path info or not, default false. | false |
77
+ | `-l` or `--log` | Whether record operation info by write file, default false. | false |
78
+ | `-o` or `--cors-origin` | Allow origin by cors, list separated by commas, must not be \* when withCredential is true .If specified, cors-headers will be `Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Data-Type,X-Requested-With,X-Data-Type,X-Auth-Token,Token` | \* |
79
+ | `-O` or `--proxy-options` | Optionally provide http request proxy options list, support accept js file、json file、cli arguments string. Examples: `-O '/api/apaas\|http://192.168.0.105:60700,/api/permission\| http://192.168.0.105:60700'`. Must start web server to use proxy for http request test under browser console or api test tools. | - |
80
+ | `-P` or `--web-port` | Web server port to use. Use `-P 9090` to look for an open port, starting at 9090 | 9090 |
81
+ | `-b` or `--web-baseurl` | Specify public path of the static web server, can be base address of SPA route. | - |
61
82
 
62
83
  ## Example
63
84
 
64
- 1. Specify server port.
85
+ 1. Specify mock server port.
65
86
 
66
87
  `mock-service-cli -p 8085`
67
88
 
68
- 2. Enable cors, specify origin and headers.
89
+ 2. Enable cors of mock server, specify the origin and headers of http request.
69
90
 
70
- `mock-service-cli -o "http://192.168.0.8:38200,http://10.30.30.3" -H "yy"`
91
+ `mock-service-cli -o "http://192.168.0.8:38200,http://10.30.30.3" -H "custom-header"`
71
92
 
72
93
  3. Specify mock directory.
73
94
 
@@ -81,6 +102,28 @@ This will install `mock-service-cli` globally so that it may be run from the com
81
102
 
82
103
  `mock-service-cli -S`
83
104
 
105
+ 6. Start static web server for SPA, and optionally specify public path and port.
106
+ `mock-service-cli -D ../react-best-practice/dist [-b '/redbridge/'] [-P 9090]`
107
+
108
+ 7. Enable Proxy base on above item 6. support accept js file、json file、cli arguments string
109
+
110
+ - cli arguments string
111
+
112
+ `mock-service-cli -D ./ -O '/api/apaas|http://192.168.0.105:60700,/api/permission|http://192.168.0.105:60700'`
113
+
114
+ - js file
115
+
116
+ `mock-service-cli -D ./ -O ./proxy.js`
117
+
118
+ proxy.js file content as follows:
119
+
120
+ ```js
121
+ module.exports = {
122
+ '/api/apaas': 'http://192.168.0.105:60700',
123
+ '/api/permission': 'http://192.168.0.105:60700'
124
+ };
125
+ ```
126
+
84
127
  ### 编写 Mock 文件
85
128
 
86
129
  > mock 请求的类型支持`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`OPTIONS`,`COPY`,`LINK`,`UNLINK`,`PURGE`
@@ -113,6 +156,8 @@ module.exports = {
113
156
 
114
157
  然后访问 `本地代理地址` + `/mock/api/222/test` (例如`http://127.0.0.1:8090/mock/api/222/test`) 就能得到 { aa: 1, bb: '使用 id 占位符' } 的响应,其他以此类推。
115
158
 
159
+ ![Mock Server](/assets/mock-server.jpg)
160
+
116
161
  ### 引入 Mock.js
117
162
 
118
163
  [Mock.js](http://mockjs.com/) 是常用的辅助生成模拟数据的三方库,借助他可以提升我们的 mock 数据能力。
@@ -141,6 +186,14 @@ module.exports = {
141
186
  };
142
187
  ```
143
188
 
189
+ ### 启动 Web Server, 在本地像 nginx 一样运行 dist 文件对应的 SPA
190
+
191
+ ![Web Server](/assets/web-server.jpg)
192
+
193
+ ### 启动 Web Server, 启用 Proxy
194
+
195
+ ![Web Server Proxy](/assets/web-server-proxy.jpg)
196
+
144
197
  ### 借助 socket.io 保留接口数据
145
198
 
146
199
  > `save-data` 和 `mock-dir-stat` 事件会自动生成 `mock-list.json` 文件(维护接口`<url, [method]>`的关系映射),方便查阅接口统计信息
@@ -2,8 +2,9 @@
2
2
 
3
3
  const colors = require('colors/safe'),
4
4
  portfinder = require('portfinder'),
5
- path = require('path'),
5
+ { resolve } = require('path'),
6
6
  nodemon = require('nodemon');
7
+ const { existsSync } = require('fs-extra');
7
8
  const argv = require('minimist')(process.argv.slice(2));
8
9
  const { logger } = require('../lib/utils');
9
10
  const spawn = require('child_process').spawn;
@@ -16,20 +17,25 @@ if (argv.h || argv.help) {
16
17
  'usage: mock-service-cli [options]',
17
18
  '',
18
19
  'options:',
19
- ' -p --port Port to use. If 0, look for open port. [8090]',
20
+ ' -p --port Mock server port to use. If 0, look for open port. [8090]',
20
21
  ' -d Specify mock directory, default [./mock] directory,',
21
22
  ' Also watch js files changes and support hot reload',
22
23
  ' -f --file Specify the input data source, support javascript ',
23
24
  ' The priority is over the directory watches',
24
- ' -s --silent Suppress log messages from output',
25
+ ' -s --silent Suppress log messages from output',
25
26
  ' -S --socket-server Whether start socket server or not, default false.',
26
- ' -a --api-stat Whether print api url and file path or not, default false.',
27
- ' -l --log Whether record operation info by write file, default false.',
28
- ' -o --cors-origin Allow origin by cors, list separated by commas, must not be * when withCredential is true',
29
- ' .If specified, cors-headers will be "Authorization,Content-Type,Accept,Origin,User-Agent,DNT',
30
- ' ,Cache-Control,X-Mx-ReqToken,X-Data-Type,X-Requested-With,X-Data-Type,X-Auth-Token,Token", default *.',
27
+ ' -a --api-stat Whether print api url and file path or not, default false.',
28
+ ' -l --log Whether record operation info by write file, default false.',
29
+ ' -o --cors-origin Allow origin by cors, list separated by commas, must not be * when withCredential is true',
30
+ ' .If specified, cors-headers will be "Authorization,Content-Type,Accept,Origin,User-Agent,DNT',
31
+ ' ,Cache-Control,X-Mx-ReqToken,X-Data-Type,X-Requested-With,X-Data-Type,X-Auth-Token,Token", default *.',
31
32
  ' -H --cors-headers Optionally provide CORS headers list separated by commas. default *',
32
33
  '',
34
+ ' -O --proxy-options Optionally provide proxy options list separated by commas.',
35
+ ' -P --web-port Web server port to use. If 0, look for open port. [9090]',
36
+ ' -D --web-dir Enable web server, specify web directory, default [./dist] directory',
37
+ ' -b --web-baseurl Specify website public path when enabled web server.',
38
+ '',
33
39
  ' -h --help Print this list and exit.',
34
40
  ' -v --version Print the version and exit.'
35
41
  ].join('\n')
@@ -53,6 +59,12 @@ if (!argv.s && !argv.silent) {
53
59
  process.env.SILENT = true;
54
60
  log = logger(true);
55
61
  }
62
+ // 注入环境变量
63
+ const injectEnvVariable = (envName, envArgs) => {
64
+ if (envArgs) {
65
+ process.env[envName] = envArgs;
66
+ }
67
+ };
56
68
 
57
69
  if (isStartSocketServer) {
58
70
  process.env.SOCKET_SERVER = true;
@@ -63,33 +75,70 @@ if (version) {
63
75
  process.exit();
64
76
  }
65
77
 
66
- if (argv.o || argv['cors-origin']) {
67
- process.env.CORS_ORIGIN = argv.o || argv.origin;
68
- }
78
+ injectEnvVariable('CORS_ORIGIN', argv.o || argv['cors-origin']);
79
+ injectEnvVariable('CORS_HEADERS', argv.H || argv['cors-headers']);
69
80
 
70
- if (argv.H || argv['cors-headers']) {
71
- process.env.CORS_HEADERS = argv.H || argv['cors-headers'];
81
+ injectEnvVariable('WEB_PUBLIC_PATH', argv.b || argv['web-baseurl']);
82
+ // injectEnvVariable('PROXY_OPTIONS', argv.O || argv['proxy-options']);
83
+ // 解析Web代理配置项(来源js|config文件或命令行参数字符串)
84
+ const proxyArg = argv.O || argv['proxy-options'];
85
+ if (proxyArg) {
86
+ const proxyTable = {};
87
+ if (proxyArg.endsWith('.js') || proxyArg.endsWith('.json')) {
88
+ const proxyOptFile = resolve(process.cwd(), proxyArg);
89
+ if (!existsSync(proxyOptFile)) {
90
+ console.error(`proxy-options: 文件 ${proxyOptFile} 不存在`);
91
+ process.exit();
92
+ }
93
+ const proxyObj = require(proxyOptFile);
94
+ Object.keys(proxyObj).forEach(function (h) {
95
+ proxyTable[h] = proxyObj[h];
96
+ }, this);
97
+ } else {
98
+ try {
99
+ proxyArg.split(/\s*,\s*/).forEach(function (h) {
100
+ const [origin, target] = h.split('|');
101
+ proxyTable[origin] = target;
102
+ }, this);
103
+ } catch (error) {
104
+ console.warn(colors.yellow('\nParse web proxy options Failed:', error));
105
+ throw error;
106
+ }
107
+ }
108
+ process.env.PROXY_OPTIONS = JSON.stringify(proxyTable);
72
109
  }
73
-
74
- if (!port) {
75
- portfinder.basePort = 8090;
110
+ if (argv.D || argv['web-dir']) {
111
+ process.env.WEB_ROOT = resolve(process.cwd(), argv.D || argv['web-dir']);
112
+ if (!existsSync(process.env.WEB_ROOT)) {
113
+ console.error(`web-dir: 目录 ${process.env.WEB_ROOT} 不存在`);
114
+ process.exit();
115
+ }
116
+ // Web Server port
117
+ portfinder.basePort = argv.P || argv['web-port'] || 9090;
76
118
  portfinder.getPort(function (err, port) {
77
119
  if (err) {
78
120
  throw err;
79
121
  }
80
- process.env.PORT = port;
122
+ process.env.WEB_PORT = port;
81
123
  });
82
- } else {
83
- process.env.PORT = port;
84
124
  }
85
125
 
126
+ // Mock Server port
127
+ portfinder.basePort = port || 8090;
128
+ portfinder.getPort(function (err, port) {
129
+ if (err) {
130
+ throw err;
131
+ }
132
+ process.env.PORT = port;
133
+ });
134
+
86
135
  const watchMockFiles = function (watchDir) {
87
136
  /**
88
137
  * script 重启的脚本
89
138
  * ext 检测的文件
90
139
  */
91
140
  nodemon({
92
- script: path.resolve(__dirname, '../lib/mockServer.js'),
141
+ script: resolve(__dirname, '../lib/mockServer.js'),
93
142
  watch: [watchDir],
94
143
  ext: 'js,json'
95
144
  });
@@ -111,20 +160,20 @@ const watchMockFiles = function (watchDir) {
111
160
  };
112
161
  // Node子进程启动MockServer
113
162
  const startMockServer = function () {
114
- spawn(node, [path.resolve(__dirname, '../lib/mockServer.js')], {
163
+ spawn(node, [resolve(__dirname, '../lib/mockServer.js')], {
115
164
  stdio: 'inherit'
116
165
  });
117
166
  };
118
167
 
119
168
  if (specifiedFile) {
120
- process.env.SPECIFIED_FILE = path.resolve(process.cwd(), specifiedFile);
169
+ process.env.SPECIFIED_FILE = resolve(process.cwd(), specifiedFile);
121
170
  if (isStartSocketServer) {
122
171
  startMockServer();
123
172
  } else {
124
173
  watchMockFiles(process.env.SPECIFIED_FILE);
125
174
  }
126
175
  } else if (watchDir) {
127
- process.env.SPECIFIED_DIR = path.resolve(process.cwd(), watchDir);
176
+ process.env.SPECIFIED_DIR = resolve(process.cwd(), watchDir);
128
177
  // log.info('SPECIFIED_DIR::', process.env.SPECIFIED_DIR);
129
178
  if (isStartSocketServer) {
130
179
  startMockServer();
@@ -132,7 +181,7 @@ if (specifiedFile) {
132
181
  watchMockFiles(process.env.SPECIFIED_DIR);
133
182
  }
134
183
  } else {
135
- watchDir = process.env.SPECIFIED_DIR = path.resolve(process.cwd(), './mock');
184
+ watchDir = process.env.SPECIFIED_DIR = resolve(process.cwd(), './mock');
136
185
  // log.info('SPECIFIED_DIR::', process.env.SPECIFIED_DIR);
137
186
  if (isStartSocketServer) {
138
187
  startMockServer();
package/lib/mockServer.js CHANGED
@@ -3,11 +3,19 @@ const express = require('express'), // 引入express
3
3
  os = require('os'),
4
4
  path = require('path'),
5
5
  colors = require('colors/safe'),
6
- portfinder = require('portfinder'),
7
- chalk = require('chalk');
6
+ portfinder = require('portfinder');
7
+ const { createProxyMiddleware } = require('http-proxy-middleware');
8
8
  const ifaces = os.networkInterfaces();
9
9
  const { Server } = require('socket.io');
10
- const { dateFormat, logger, SupportMethods, getFileLatestContent, filePath2ApiUrl, isEmptyObj } = require('./utils');
10
+ const {
11
+ dateFormat,
12
+ logger,
13
+ SupportMethods,
14
+ DefaultHeaders,
15
+ getFileLatestContent,
16
+ filePath2ApiUrl,
17
+ isEmptyObj
18
+ } = require('./utils');
11
19
  const { genMockFiles, getMockStatFromDir, getMockStatFromFile } = require('./manageMockFiles');
12
20
 
13
21
  const methodRegExp = new RegExp(`(${SupportMethods.join('|')}) +(.*)`, 'i');
@@ -46,12 +54,12 @@ if (process.env.CORS_ORIGIN) {
46
54
  process.env.CORS_ORIGIN.split(/\s*,\s*/).forEach(function (h) {
47
55
  corsOrigin.push(h);
48
56
  }, this);
49
- corsHeaders =
50
- 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Data-Type,X-Requested-With,X-Data-Type,X-Auth-Token,Token';
57
+
58
+ corsHeaders = DefaultHeaders;
51
59
  }
52
60
  if (process.env.CORS_HEADERS) {
53
61
  process.env.CORS_HEADERS.split(/\s*,\s*/).forEach(function (h) {
54
- corsHeaders += ', ' + h;
62
+ corsHeaders += corsHeaders ? ', ' + h : h;
55
63
  }, this);
56
64
  }
57
65
  /**
@@ -143,13 +151,62 @@ const parseMockFiles = function (specialDir = '../mock') {
143
151
  composeRouteFromJsFile(filePath);
144
152
  }
145
153
  };
154
+
155
+ // 允许跨域
146
156
  app.use(crossDomain());
157
+
147
158
  if (process.env.SPECIFIED_FILE) {
148
159
  composeRouteFromJsFile(process.env.SPECIFIED_FILE);
149
160
  } else {
150
161
  parseMockFiles(process.env.SPECIFIED_DIR);
151
162
  }
152
- argv.a && log.info(chalk.hex('#ce5b34bd')(`${fileCount} mock file are parsed in total.`));
163
+ argv.a && log.info(colors.yellow(`${fileCount} mock file are parsed in total.`));
164
+
165
+ let webApp = null,
166
+ webPublicPath = '/',
167
+ proxyTable = {};
168
+ // Enable Web Server
169
+ if (process.env.WEB_ROOT) {
170
+ webApp = express();
171
+ // Enable web proxy
172
+ if (process.env.PROXY_OPTIONS) {
173
+ try {
174
+ const options = JSON.parse(process.env.PROXY_OPTIONS);
175
+ Object.keys(options).forEach(function (origin) {
176
+ proxyTable[origin] = options[origin];
177
+ // 接口代理
178
+ webApp.use(origin, createProxyMiddleware({ target: options[origin], changeOrigin: true, ws: true }));
179
+ }, this);
180
+ } catch (error) {
181
+ console.warn(colors.yellow('\nEnable web proxy Failed:', error));
182
+ }
183
+ }
184
+ // console.log(process.env.WEB_PUBLIC_PATH, process.env.WEB_ROOT);
185
+ if (process.env.WEB_PUBLIC_PATH) {
186
+ webPublicPath = process.env.WEB_PUBLIC_PATH;
187
+ }
188
+ webApp.use(webPublicPath, express.static(process.env.WEB_ROOT)); // 将dist目录下所有文件作为静态文件来管理
189
+ const defaultStaticEntry = `${process.env.WEB_ROOT}/index.html`;
190
+ if (fs.existsSync(defaultStaticEntry)) {
191
+ webApp.get('*', (req, res) => {
192
+ res.sendFile(defaultStaticEntry);
193
+ });
194
+ } else {
195
+ webApp.use(webPublicPath, (req, res) => {
196
+ res.status(200)
197
+ .send(`Hi, welcome to web server entrance ui, you can test http proxy on browser console or api request tools. Examples as follows:<br />
198
+ fetch("http://localhost:${process.env.WEB_PORT}/api/permission/auth/login", {
199
+ method: 'post',
200
+ headers: {
201
+ "accept": "*/*",
202
+ "Content-type": "application/json; charset=UTF-8",
203
+ },
204
+ body:JSON.stringify({"loginName":"admin","password":"admin"})
205
+ })
206
+ `);
207
+ });
208
+ }
209
+ }
153
210
  const http = require('http').createServer(app);
154
211
  if (process.env.SOCKET_SERVER) {
155
212
  socketServer = new Server(http, { path: '/ws/mock-service' });
@@ -209,7 +266,8 @@ http.listen(Number.parseInt(process.env.PORT, 10), () => {
209
266
  console.info(
210
267
  [colors.yellow('\n🌍 mock-server version: '), colors.cyan(require('../package.json').version), '\n'].join('')
211
268
  );
212
-
269
+ console.info(colors.yellow(`\n Mock server available on:\n`));
270
+ console.info(' http://localhost:' + colors.green(process.env.PORT));
213
271
  Object.keys(ifaces).forEach(function (dev) {
214
272
  ifaces[dev].forEach(function (details) {
215
273
  if (details.family === 'IPv4') {
@@ -220,6 +278,26 @@ http.listen(Number.parseInt(process.env.PORT, 10), () => {
220
278
  }
221
279
  });
222
280
 
281
+ if (webApp && !process.env.RESTARTED) {
282
+ webApp.listen(Number.parseInt(process.env.WEB_PORT, 10), () => {
283
+ console.info(colors.yellow(`\n Web server available on:\n`));
284
+ console.info(' http://localhost:' + colors.green(process.env.WEB_PORT) + webPublicPath);
285
+ Object.keys(ifaces).forEach(function (dev) {
286
+ ifaces[dev].forEach(function (details) {
287
+ if (details.family === 'IPv4') {
288
+ console.info(' http://' + details.address + ':' + colors.green(process.env.WEB_PORT) + webPublicPath);
289
+ }
290
+ });
291
+ });
292
+ if (!isEmptyObj(proxyTable)) {
293
+ console.info(colors.yellow(`\n Enable proxy at web server on:`));
294
+ Object.keys(proxyTable).forEach(origin => {
295
+ console.info(` ${origin} -> ${proxyTable[origin]}`);
296
+ });
297
+ }
298
+ });
299
+ }
300
+
223
301
  if (process.platform === 'win32') {
224
302
  require('readline')
225
303
  .createInterface({
package/lib/utils.js CHANGED
@@ -86,7 +86,8 @@ function logger(isSilent = false) {
86
86
  }
87
87
  // MockServer 支持的请求类型
88
88
  const SupportMethods = ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'PATCH', 'OPTIONS', 'COPY', 'LINK', 'UNLINK', 'PURGE'];
89
-
89
+ const DefaultHeaders =
90
+ 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Data-Type,X-Requested-With,X-Data-Type,X-Auth-Token,Token';
90
91
  const isValidMethod = function (m) {
91
92
  return SupportMethods.includes(String(m).toLocaleUpperCase());
92
93
  };
@@ -279,6 +280,7 @@ module.exports = {
279
280
  dateFormat,
280
281
  logger,
281
282
  SupportMethods,
283
+ DefaultHeaders,
282
284
  isValidMethod,
283
285
  getFileLatestContent,
284
286
  filePath2ApiUrl,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mock-service-cli",
3
- "version": "2.5.1",
3
+ "version": "3.1.2",
4
4
  "description": "🦅 Local mock server",
5
5
  "main": "./lib/mockServer.js",
6
6
  "bin": {
@@ -49,9 +49,10 @@
49
49
  "deasync": "^0.1.23",
50
50
  "express": "^4.17.1",
51
51
  "fs-extra": "^10.0.0",
52
+ "http-proxy-middleware": "^2.0.6",
52
53
  "lodash": "^4.17.21",
53
- "minimist": "^1.2.5",
54
- "nodemon": "^2.0.14",
54
+ "minimist": "^1.2.6",
55
+ "nodemon": "^2.0.19",
55
56
  "portfinder": "^1.0.28",
56
57
  "socket.io": "^4.4.0"
57
58
  },