{"id":21182267,"url":"https://github.com/tangxiangmin/mock-server","last_synced_at":"2025-07-10T00:32:13.478Z","repository":{"id":57160141,"uuid":"141777727","full_name":"tangxiangmin/mock-server","owner":"tangxiangmin","description":"a convenient local mock data server","archived":false,"fork":false,"pushed_at":"2020-07-26T15:34:12.000Z","size":39,"stargazers_count":13,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"master","last_synced_at":"2024-11-14T16:44:39.759Z","etag":null,"topics":["mock","mock-server","mockjs"],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tangxiangmin.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-07-21T03:21:13.000Z","updated_at":"2021-11-08T09:09:43.000Z","dependencies_parsed_at":"2022-09-08T19:01:48.131Z","dependency_job_id":null,"html_url":"https://github.com/tangxiangmin/mock-server","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tangxiangmin%2Fmock-server","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tangxiangmin%2Fmock-server/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tangxiangmin%2Fmock-server/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tangxiangmin%2Fmock-server/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tangxiangmin","download_url":"https://codeload.github.com/tangxiangmin/mock-server/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225606641,"owners_count":17495551,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["mock","mock-server","mockjs"],"created_at":"2024-11-20T17:56:17.592Z","updated_at":"2024-11-20T17:56:18.451Z","avatar_url":"https://github.com/tangxiangmin.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"mock-server\n===\n\n为开发环境快速搭建koa服务器，只需要一个mock模板文件即可。\n\n脚本将启动本地服务器，然后匹配mock模板内的url返回对应的数据\n\n## 使用\n```\n# 全局安装\nnpm i @shymean/mock-server -g\n# 快速启动mock服务器\nmock -p 9999 -f ./_mock.js\n```\n参数说明\n* port，服务器端口号，默认7654，简写 -p\n* file，mock模板文件路径，默认`./_mock.js`，简写 -f\n\n## mockjs模板语法\n使用该工具只需要准备一个mock模板文件，其语法参考\n* 内部使用[@shymean/koa-mock`](https://www.npmjs.com/package/@shymean/koa-mock)，这是一个快速搭建koa的mock服务器的中间件\n* mock模板使用[mockjs语法](https://www.npmjs.com/package/mockjs)，并扩展了相关的功能\n\n### 基础使用\n其使用方式与mockjs基本类似\n* `Mock.mock(url, template)`\n* `Mock.mock(url, method, template)`\n\n```js\n// _mock.js\n// 对应的rurl会被中间件拦截，并返回mock数据\n// ANY localhost:9999/\nMock.mock('/', {\n    data: [],\n    msg: \"hello mock\",\n    \"code|1-4\": 1,\n})\n\n// 可以mock指定的请求方法\n// POST localhost:9999/test\nMock.mock('/test', 'POST', {\n    data: [],\n    msg: \"hello mock\",\n    \"code|1-4\": 1,\n})\n\n// 扩展rtype，支持jsonp形式，使用param传入对应的回调名\n// GET JSONP localhost:9999/test\nMock.mock('/test', {\n    type: 'jsonp',\n    param: 'callbackName'\n},{\n    code: 0,\n    msg: 'hello from mock jsonp',\n    data: {\n        \"id|1000-9999\": 1,\n    }\n})\n\n// 默认回调名称 callback\nMock.mock(\"/test2\", \"jsonp\", {\n    code: 0,\n    msg: \"hello from mock jsonp2\",\n    data: {\n        \"id|1000-9999\": 1,\n    }\n});\n```\n\n### 自定义请求头匹配\n有时候某个相同的url请求，根据业务参数需要返回不同的模拟数据，因此提供了自定义匹配请求url的功能，需要在模板文件中实现`Mock.parseUrl`方法即可，该方法返回一个用于匹配的rurl\n\n```js\nMock.parseUrl = function(ctx){\n    // ctx为koa上下文对象\n    return 'someUrl'\n}\n\nMock.mock('someUrl', {code: 0})\n```\n\n### 获取自定义请求详情\n在某些时候需要根据请求详情（如请求参数、cookie等）返回不同的模拟数据，因此提供了**函数模板**，其中`Koa`请求上下文将通过参数的方式注入\n\n```js\nMock.mock(/auth/, (ctx) =\u003e {\n    let {uid} = ctx.query\n    if (uid) {\n        return {\n            code: 200,\n            msg: 'success',\n            data: {\n                uid\n            }\n        }\n    } else {\n        return {\n            code: 401,\n            msg: 'no uid',\n        }\n    }\n})\n```\n注：该功能看起来与上面提供的`parseUrl`方法比较类似，但区别在于：`parseUrl`主要用于批量指定解析rurl的模式，而函数模板主要用于针对单个url的请求动态返回模拟数据\n### loadModule\n\n由于内部使用`eval`执行模板文件，因此在模板文件中使用`require`导入的其他模块（如很大一段JSON模拟数据）路径可能存在问题，\n\n解决办法是使用`process.cwd()`+`path.resolve`显式指定模块路径\n```js\nconst path = require('path')\nlet list = require(path.resolve(process.cwd(), './example/list.json'))\n\nMock.mock(/list/, {data:list})\n```\n\n因此，工具内置了`Mock.loadModule`方法，用于导入其他模块\n```js\nlet list = Mock.loadModule('./example/list.json')\nMock.mock(/list/, {data:list})\n```\n\n### nginx配置\n\n为了避免在业务代码中使用localhost域名，最佳实践方案是开发时将业务域名（如`xxx.test.com`）指向本地\n\n```\n127.0.0.1 xxx.test.com\n```\n然后通过nginx配置反向代理到mock服务器\n```nginx\nserver {\n    listen 80;\n    server_name xxx.test.com;\n\n    # wireless_j项目中的活动接口\n    location /j/cn/control/api {\n        proxy_set_header X-Real-IP $remote_addr;\n        proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;\n        proxy_set_header Host $http_host;\n        proxy_pass http://127.0.0.1:9999; # mock -p 9999 指令启动的服务器的端口号\n    }\n}\n```\n\n## Feature\n* [x] 与mockjs浏览器端共用同一套mock模板，方便迁移和代码维护\n* [x] 支持jsonp请求\n* [x] 数据模板热更新，修改模板文件后，将自动重启服务器\n* [x] 根据请求信息，动态返回模板数据\n\n## Todo\n* [ ] 支持映射本地文件，比如样式表、图片等\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftangxiangmin%2Fmock-server","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftangxiangmin%2Fmock-server","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftangxiangmin%2Fmock-server/lists"}