{"id":14976434,"url":"https://github.com/jaywcjlove/mocker-api","last_synced_at":"2025-05-14T13:04:22.010Z","repository":{"id":29242339,"uuid":"120641823","full_name":"jaywcjlove/mocker-api","owner":"jaywcjlove","description":"mocker-api that creates mocks for REST APIs. It will be helpful when you try to test your application without the actual REST API server.","archived":false,"fork":false,"pushed_at":"2025-04-04T04:56:05.000Z","size":6038,"stargazers_count":489,"open_issues_count":28,"forks_count":65,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-05-09T12:22:48.981Z","etag":null,"topics":["mock-data","mock-server","mockjs","mockup","webpack","webpack-dev-server","webpack3","webpack4"],"latest_commit_sha":null,"homepage":"https://jaywcjlove.github.io/mocker-api","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jaywcjlove.png","metadata":{"files":{"readme":"README-zh.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"ko_fi":"jaywcjlove","buy_me_a_coffee":"jaywcjlove","custom":["https://www.paypal.me/kennyiseeyou","https://jaywcjlove.github.io/#/sponsor"]}},"created_at":"2018-02-07T16:37:03.000Z","updated_at":"2025-04-05T17:43:01.000Z","dependencies_parsed_at":"2024-02-04T18:07:38.482Z","dependency_job_id":"c0fb9218-9ef2-467f-afe9-e632b0f810f5","html_url":"https://github.com/jaywcjlove/mocker-api","commit_stats":{"total_commits":523,"total_committers":24,"mean_commits":"21.791666666666668","dds":"0.37476099426386233","last_synced_commit":"07892df71073b86d37d4a651e9418496eb463f80"},"previous_names":["jaywcjlove/webpack-api-mocker"],"tags_count":79,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jaywcjlove%2Fmocker-api","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jaywcjlove%2Fmocker-api/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jaywcjlove%2Fmocker-api/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jaywcjlove%2Fmocker-api/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jaywcjlove","download_url":"https://codeload.github.com/jaywcjlove/mocker-api/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254036842,"owners_count":22003654,"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-data","mock-server","mockjs","mockup","webpack","webpack-dev-server","webpack3","webpack4"],"created_at":"2024-09-24T13:53:52.915Z","updated_at":"2025-05-14T13:04:21.962Z","avatar_url":"https://github.com/jaywcjlove.png","language":"JavaScript","funding_links":["https://ko-fi.com/jaywcjlove","https://buymeacoffee.com/jaywcjlove","https://www.paypal.me/kennyiseeyou","https://jaywcjlove.github.io/#/sponsor"],"categories":["JavaScript"],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://uiwjs.github.io/npm-unpkg/#/pkg/mocker-api/file/README.md\"\u003e\n    \u003cimg alt=\"Mocker API LOGO\" src=\"https://github.com/user-attachments/assets/68d24ccf-2100-41b8-8ff2-96397c6cee77\" /\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://jaywcjlove.github.io/#/sponsor\"\u003e\n    \u003cimg alt=\"Buy me a coffee\" src=\"https://img.shields.io/badge/Buy%20me%20a%20coffee-048754?logo=buymeacoffee\" /\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://github.com/jaywcjlove/mocker-api/actions\"\u003e\n    \u003cimg alt=\"Build \u0026 Deploy\" src=\"https://github.com/jaywcjlove/mocker-api/actions/workflows/ci.yml/badge.svg\" /\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://www.npmjs.com/package/mocker-api\"\u003e\n    \u003cimg alt=\"Download\" src=\"https://img.shields.io/npm/dm/mocker-api.svg?style=flat\" /\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://github.com/jaywcjlove/mocker-api/network/dependents\"\u003e\n    \u003cimg alt=\"Repo Dependents\" src=\"https://badgen.net/github/dependents-repo/jaywcjlove/mocker-api\" /\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://uiwjs.github.io/npm-unpkg/#/pkg/mocker-api/file/README.md\"\u003e\n    \u003cimg src=\"https://img.shields.io/badge/Open%20in-unpkg-blue\" alt=\"Open in unpkg\" /\u003e\n  \u003c/a\u003e\n  \u003ca href=\"https://gitee.com/jaywcjlove/mocker-api\"\u003e\n    \u003cimg alt=\"Release\" src=\"https://jaywcjlove.github.io/sb/ico/gitee.svg\" /\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"README.md\"\u003eEnglish\u003c/a\u003e · \n  \u003ca href=\"#快速开始\"\u003e快速开始\u003c/a\u003e · \n  \u003ca href=\"#使用\"\u003e使用\u003c/a\u003e · \n  \u003ca href=\"#参数设置\"\u003e参数设置\u003c/a\u003e · \n  \u003ca href=\"#延迟响应\"\u003e延迟响应\u003c/a\u003e · \n  \u003ca href=\"#实例\"\u003e实例\u003c/a\u003e · \n  \u003ca href=\"#license\"\u003eLicense\u003c/a\u003e · \n  \u003ca href=\"https://jaywcjlove.github.io/mocker-api/type/\" target=\"__blank\"\u003eType\u003c/a\u003e\n\u003c/p\u003e\n\n`mocker-api` 用于创建 REST API 的模拟。当你需要在没有实际 REST API 服务器的情况下测试你的应用程序时，它会非常有用。\n\n**特点：**  \n\n🔥 内置对热替换 Mocker 文件的支持。  \n🚀 通过 JSON 快速轻松地配置 API。  \n🌱 简化的 Mock API 代理。  \n💥 可以独立使用，不依赖于 [webpack](https://github.com/webpack/webpack) 和 [webpack-dev-server](https://github.com/webpack/webpack-dev-server)。\n\n## 快速开始\n\n```bash\nmkdir mocker-app \u0026\u0026 cd mocker-app\n\n# 根据规则创建模拟程序配置文件\ntouch api.js\n\n# 全局安装。\nnpm install mocker-api -g\n# 运行服务\nmocker ./api.js\n\n# Run server at localhost:8000\nmocker ./api.js --host localhost --port 8000\n```\n\n## 安装\n\n您可以将其 `package.json` 配置作为当前项目依赖项。\n\n```bash\nnpm install mocker-api --save-dev\n```\n\n## 使用\n\n`mocker-api` 支持模拟，在 `mocker / index.js` 中配置。\n\n您可以修改 [http-proxy](https://www.npmjs.com/package/http-proxy) 选项并通过添加 `httpProxy` 配置来添加事件监听器\n\n```js\nconst proxy = {\n  // 优先处理。\n  // apiMocker(app, path, option)\n  // 这是 apiMocker 的选项参数设置 `option`\n  _proxy: {\n    proxy: {\n      // 将路径字符串（例如`/user/:name`）转换为正则表达式。\n      // https://www.npmjs.com/package/path-to-regexp\n      '/repos/(.*)': 'https://api.github.com/',\n      '/:owner/:repo/raw/:ref/(.*)': 'http://127.0.0.1:2018',\n      '/api/repos/(.*)': 'http://127.0.0.1:3721/'\n    },\n    // 重写目标网址路径。对象键将用作RegEx来匹配路径。\n    // https://github.com/jaywcjlove/mocker-api/issues/62\n    pathRewrite: {\n      '^/api/repos/': '/repos/',\n    },\n    changeHost: true,\n    // 修改 http-proxy 选项\n    httpProxy: {\n      options: {\n        ignorePath: true,\n      },\n      listeners: {\n        proxyReq: function (proxyReq, req, res, options) {\n          console.log('proxyReq');\n        },\n      },\n    },    \n  },\n  // =====================\n  // 默认的 GET 请求。\n  // https://github.com/jaywcjlove/mocker-api/pull/63\n  '/api/user': {\n    id: 1,\n    username: 'kenny',\n    sex: 6\n  },\n  'GET /api/user': {\n    id: 1,\n    username: 'kenny',\n    sex: 6\n  },\n  'GET /api/user/list': [\n    {\n      id: 1,\n      username: 'kenny',\n      sex: 6\n    }, {\n      id: 2,\n      username: 'kenny',\n      sex: 6\n    }\n  ],\n  'GET /api/:owner/:repo/raw/:ref/(.*)': (req, res) =\u003e {\n    const { owner, repo, ref } = req.params;\n    // http://localhost:8081/api/admin/webpack-mock-api/raw/master/add/ddd.md\n    // owner =\u003e admin\n    // repo =\u003e webpack-mock-api\n    // ref =\u003e master\n    // req.params[0] =\u003e add/ddd.md\n    return res.json({\n      id: 1,\n      owner, repo, ref,\n      path: req.params[0]\n    });\n  },\n  'POST /api/login/account': (req, res) =\u003e {\n    const { password, username } = req.body;\n    if (password === '888888' \u0026\u0026 username === 'admin') {\n      return res.json({\n        status: 'ok',\n        code: 0,\n        token: \"sdfsdfsdfdsf\",\n        data: {\n          id: 1,\n          username: 'kenny',\n          sex: 6\n        }\n      });\n    } else {\n      return res.status(403).json({\n        status: 'error',\n        code: 403\n      });\n    }\n  },\n  'DELETE /api/user/:id': (req, res) =\u003e {\n    console.log('----\u003e', req.body)\n    console.log('----\u003e', req.params.id)\n    res.send({ status: 'ok', message: '删除成功！' });\n  }\n}\nmodule.exports = proxy;\n```\n\n## 参数设置 \n\n- [`proxy`](https://www.npmjs.com/package/path-to-regexp) =\u003e `{}` Proxy settings, Turn a path string such as `/user/:name` into a regular expression.\n- [`pathRewrite`](https://github.com/jaywcjlove/mocker-api/issues/62) =\u003e `{}` rewrite target's url path. Object-keys will be used as RegExp to match paths. [#62](https://github.com/jaywcjlove/mocker-api/issues/62)\n- `withFullUrlPath=false` =\u003e `Boolean` the proxy regular expression support full url path. if the proxy regular expression like `/test?a=1\u0026b=1` can be matched. [#25](https://github.com/jaywcjlove/mocker-api/issues/25)\n- `priority` =\u003e `proxy` priority `proxy` or `mocker` [#151](https://github.com/jaywcjlove/mocker-api/issues/151)\n- `changeHost` =\u003e `Boolean` Setting req headers host.\n- `httpProxy` =\u003e `{}` Set the [listen event](https://github.com/nodejitsu/node-http-proxy#listening-for-proxy-events) and [configuration](https://github.com/nodejitsu/node-http-proxy#options) of [http-proxy](https://github.com/nodejitsu/node-http-proxy)    \n- [`bodyParserJSON`](https://github.com/expressjs/body-parser/tree/56a2b73c26b2238bc3050ad90af9ab9c62f4eb97#bodyparserjsonoptions) JSON body parser\n- [`bodyParserText`](https://github.com/expressjs/body-parser/tree/56a2b73c26b2238bc3050ad90af9ab9c62f4eb97#bodyparsertextoptions) Text body parser\n- [`bodyParserRaw`](https://github.com/expressjs/body-parser/tree/56a2b73c26b2238bc3050ad90af9ab9c62f4eb97#bodyparserrawoptions) Raw body parser\n- [`bodyParserUrlencoded`](https://github.com/expressjs/body-parser/tree/56a2b73c26b2238bc3050ad90af9ab9c62f4eb97#bodyparserurlencodedoptions) URL-encoded form body parser\n- `bodyParserConf` =\u003e `{}` bodyParser settings. eg： `bodyParserConf : {'text/plain': 'text','text/html': 'text'}` will parsed `Content-Type='text/plain' and Content-Type='text/html'` with `bodyParser.text`  \n- [`watchOptions`](https://github.com/paulmillr/chokidar#api) =\u003e `object` Options object as defined [chokidar api options](https://github.com/paulmillr/chokidar#api)\n- `header` =\u003e `{}` Access Control Allow options.\n  ```js\n  {\n    header: {\n      'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE',\n    }\n  }\n  ```\n\n⚠️ No wildcard asterisk ~~`*`~~ - use parameters instead `(.*)`, support `v1.7.3+`\n\n## 延迟响应\n\n您可以使用功能性工具来增强模拟效果。[#17](https://github.com/jaywcjlove/webpack-api-mocker/issues/17)\n\n```js\nconst delay = require('mocker-api/delay');\nconst noProxy = process.env.NO_PROXY === 'true';\n\nconst proxy = {\n  'GET /api/user': {\n    id: 1,\n    username: 'kenny',\n    sex: 6\n  },\n  // ...\n}\nmodule.exports = (noProxy ? {} : delay(proxy, 1000));\n```\n\n## apiMocker\n\n```js\napiMocker(app, mockerFilePath[, options])\napiMocker(app, Mocker[, options])\n```\n\n多个模拟文件监听\n\n```js\nconst apiMocker = require('mocker-api');\nconst mockerFile = ['./mock/index.js'];\n// or\n// const mockerFile = './mock/index.js';\napiMocker(app, mockerFile, options)\n```\n\n## 实例\n\n### 在命令行中使用\n\n[Base example](example/base)\n\n\u003e⚠️  Not dependent on [webpack](https://github.com/webpack/webpack) and [webpack-dev-server](https://github.com/webpack/webpack-dev-server). \n\n```bash\n# Global install dependent.\nnpm install mocker-api -g\n# Run server\nmocker ./mocker/index.js\n```\n\nOr you can put it the `package.json` config as a current project dependency.\n\n```diff\n{\n  \"name\": \"base-example\",\n  \"scripts\": {\n+    \"api\": \"mocker ./mocker\"\n  },\n  \"devDependencies\": {\n+    \"mocker-api\": \"2.9.5\"\n  },\n  \"license\": \"MIT\"\n}\n```\n\n### 在 [Express](https://github.com/expressjs/express) 中使用\n\n[Express example](https://github.com/jaywcjlove/mocker-api/tree/master/example/express)\n\n\u003e⚠️  Not dependent on [webpack](https://github.com/webpack/webpack) and [webpack-dev-server](https://github.com/webpack/webpack-dev-server).\n\n```diff\nconst express = require('express');\n+ const path = require('path');\n+ const apiMocker = require('mocker-api');\n\nconst app = express();\n\n+ apiMocker(app, path.resolve('./mocker/index.js'))\napp.listen(8080);\n```\n\nor\n\n```diff\nconst express = require('express');\n+ const apiMocker = require('mocker-api');\n\nconst app = express();\n\n+ apiMocker(app, {\n+   'GET /api/user': {\n+     id: 1,\n+     sex: 0\n+   }\n+ });\n\napp.listen(8080);\n```\n\n### 在 [Webpack](https://github.com/webpack/webpack) 中使用\n\n[webpack example](https://github.com/jaywcjlove/mocker-api/tree/master/example/webpack)\n\nTo use api mocker on your [Webpack](https://github.com/webpack/webpack) projects, simply add a setup options to your [webpack-dev-server](https://github.com/webpack/webpack-dev-server) options:\n\nChange your config file to tell the dev server where to look for files: `webpack.config.js`.\n\n```diff\nconst HtmlWebpackPlugin = require('html-webpack-plugin');\n+ const path = require('path');\n+ const apiMocker = require('mocker-api');\n\nmodule.exports = {\n  entry: {\n    app: './src/index.js',\n  },\n  output: {\n    filename: '[name].bundle.js',\n    path: path.resolve(__dirname, 'dist')\n  },\n+ devServer: {\n+   ...\n+   before(app){\n+     apiMocker(app, path.resolve('./mocker/index.js'), {\n+       proxy: {\n+         '/repos/*': 'https://api.github.com/',\n+         '/:owner/:repo/raw/:ref/*': 'http://127.0.0.1:2018'\n+       },\n+       changeHost: true,\n+     })\n+   }\n+ },\n  plugins: [\n    new HtmlWebpackPlugin({\n      template: path.resolve('./public/index.html'),\n      title: 'Webpack App Mocker API'\n    })\n  ],\n};\n```\n\nMust have a file suffix! For example: `./mocker/index.js`.\n\nLet's add a script to easily run the dev server as well: `package.json`\n\n```diff\n{\n  \"name\": \"development\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"webpack.config.js\",\n  \"scripts\": {\n    \"test\": \"echo \\\"Error: no test specified\\\" \u0026\u0026 exit 1\",\n+    \"start\": \"webpack serve --progress --mode development\",\n    \"build\": \"webpack --mode production\"\n  },\n  \"keywords\": [],\n  \"author\": \"\",\n  \"license\": \"MIT\",\n  \"devDependencies\": {\n    \"html-webpack-plugin\": \"4.5.0\",\n    \"mocker-api\": \"2.9.5\",\n    \"webpack\": \"5.22.0\",\n    \"webpack-cli\": \"4.5.0\",\n    \"webpack-dev-server\": \"3.11.2\"\n  }\n}\n```\n\nMock API proxying made simple.\n\n```diff\n{\n  before(app){\n+   apiMocker(app, path.resolve('./mocker/index.js'), {\n+     proxy: {\n+       '/repos/*': 'https://api.github.com/',\n+     },\n+     changeHost: true,\n+   })\n  }\n}\n```\n\n###  在 create-react-app 中使用\n\n[create-react-app example](https://github.com/jaywcjlove/mocker-api/tree/master/example/create-react-app)\n\n创建 [`src/setupProxy.js`](https://github.com/jaywcjlove/mocker-api/blob/64a093685b05c70ab0ddcf3fd5dbede7871efa8a/example/create-react-app/src/setupProxy.js#L1-L11) 并放置以下内容：\n\n```diff\n+ const apiMocker = require('mocker-api');\n+ const path = require('path');\n\nmodule.exports = function(app) {\n+  apiMocker(app, path.resolve('./mocker/index.js'), {\n+    proxy: {\n+      '/repos/(.*)': 'https://api.github.com/',\n+    },\n+    changeHost: true,\n+  });\n};\n```\n\n```diff\n{\n  .....\n  \"devDependencies\": {\n+    \"mocker-api\": \"2.9.5\"\n  },\n  ....\n}\n```\n\n\n### 开发\n\n```shell\n$ yarn install\n$ yarn run build\n$ yarn run watch\n$ yarn run test\n```\n\n## Contributors\n\nAs always, thanks to our amazing contributors!\n\n\u003ca href=\"https://github.com/jaywcjlove/mocker-api/graphs/contributors\"\u003e\n  \u003cimg src=\"https://jaywcjlove.github.io/mocker-api/CONTRIBUTORS.svg\" /\u003e\n\u003c/a\u003e\n\nMade with [github-action-contributors](https://github.com/jaywcjlove/github-action-contributors).\n\n## License\n\n[MIT © Kenny Wong](https://github.com/jaywcjlove/mocker-api/blob/master/LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjaywcjlove%2Fmocker-api","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjaywcjlove%2Fmocker-api","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjaywcjlove%2Fmocker-api/lists"}