{"id":30275973,"url":"https://github.com/wuhy/autoresponse","last_synced_at":"2025-08-16T10:52:50.724Z","repository":{"id":17901716,"uuid":"20857271","full_name":"wuhy/autoresponse","owner":"wuhy","description":"Autoresponse middleware using local data or proxy to mock request","archived":false,"fork":false,"pushed_at":"2024-03-16T01:34:38.000Z","size":308,"stargazers_count":13,"open_issues_count":1,"forks_count":3,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-07-17T03:11:48.706Z","etag":null,"topics":["edp","express","middleware","mock","webpack"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","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/wuhy.png","metadata":{"files":{"readme":"README.md","changelog":"history.md","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":"2014-06-15T14:31:32.000Z","updated_at":"2022-09-14T04:09:51.000Z","dependencies_parsed_at":"2022-09-09T05:11:14.994Z","dependency_job_id":null,"html_url":"https://github.com/wuhy/autoresponse","commit_stats":null,"previous_names":[],"tags_count":19,"template":false,"template_full_name":null,"purl":"pkg:github/wuhy/autoresponse","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wuhy%2Fautoresponse","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wuhy%2Fautoresponse/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wuhy%2Fautoresponse/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wuhy%2Fautoresponse/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/wuhy","download_url":"https://codeload.github.com/wuhy/autoresponse/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wuhy%2Fautoresponse/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":270702483,"owners_count":24630874,"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","status":"online","status_checked_at":"2025-08-16T02:00:11.002Z","response_time":91,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":["edp","express","middleware","mock","webpack"],"created_at":"2025-08-16T10:52:45.905Z","updated_at":"2025-08-16T10:52:50.712Z","avatar_url":"https://github.com/wuhy.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# autoresponse [![NPM Version](https://img.shields.io/npm/v/autoresponse.svg?style=flat)](https://npmjs.org/package/autoresponse)\n\n\u003e A connect middleware for mocking the http request, can used in `edp-webserver` or `webpack-dev-server` mocking\n\n## Install\n\n**Require Node.js 8+**\n\n```shell\nnpm install autoresponse\n```\n\n## Usage\n\nThe `autoresponse` mock config, you can specify by a `autoresponse-config.js` config file or passing the mock config params.\n\n```javascript\nvar autoresponse = require(\"autoresponse\")({\n    logLevel: \"info\", // the level to print log info\n    post: true, // mock all post request\n    patch: true, // mock all patch request\n    get: {\n        match: function(reqPathName) {\n            // mock all `/xx/xx` path\n            return !/\\.\\w+(\\?.*)?$/.test(reqPathName);\n        }\n    },\n\n    // or using rules options, support request methods setting\n    // the rules option priority is higher than the outside `get`/`post`/... request\n    // method mock rule\n    rules: [\n        {\n            // by default mock all methods, if method option is not set\n            match: \"/users/:id\", // by default use `users.js` mock file\n            method: [\"get\", \"patch\"]\n        },\n        {\n            match: function(reqPathName, reqMethod) {\n                return true;\n            },\n            mock: function(reqPathName, reqMethod) {\n                return \"custom/myMockFile.js\";\n            },\n            method: \"post\"\n        }\n    ]\n});\n```\n\nBy default the mock file path is the same as the request url pathname, e.g., the request pathname is `/a/b`, the default mock file path is `\u003cprojectRoot\u003e/mock/a/b.js`. If the mock file is not existed, `autoresponse` will auto create the mock file basing the mock file template.\n\nThe mock file like this:\n\n```javascript\nmodule.exports = function(path, queryParam, postParam, context) {\n    return {\n        timeout: 50, // response timeout, unit is millisecond, default is 0\n        _timeout: 50, // The same as timeout\n        _status: 200, // The response http status code, by default 200\n        _header: {}, // The response header\n        _data: {}, // The response mock data\n        _jsonp: false, // response jsonp\n        _callback: \"callback\" // The jsonp callback param name, default: callback\n    };\n\n    // mock data placed in `_data` is not required, the following is also valid\n    // return {\n    //    timeout: 10,\n    //    status: 0,\n    //    statusInfo: {}\n    // };\n};\n```\n\nIf the same request need to mock different request method, you can also write the mock data, like this:\n\n```javascript\nmodule.exports = {\n    // mock the post request\n    post: function(path, queryParam, postParam, context) {\n        var params = context.params; // the restful path param\n        return {\n            // ...\n        };\n    },\n\n    // mock the patch request\n    patch: {\n        status: 0,\n        statusInfo: \"patch ok\"\n    }\n};\n```\n\n`Autoresponse` supports any file types mocking, you can using `js file`, `json file` or any other custom mock syntax to generate the mock data. For example, you can using `js` to mock `smarty` template without needing `php` programming. If there is none available mock handler, you can also custom it by yourself.\n\nMoreover, `autoresponse` provide some useful [mock helpers](#helper) to help generating mock data.\n\n**Tip:** If you need modify the mock config frequently, the best choice is using `autoresponse-config.js` config file, `autoresponse` support auto reload config file by using `watch: true` option without having to restart the dev server. The more usage information you can see [here](#config-file).\n\nThe more detail usage, you can see [examples](https://github.com/wuhy/autoresponse/tree/master/examples).\n\n## Using as a connect middleware\n\n```javascript\nvar autoresponse = require(\"autoresponse\")({\n    logLevel: \"info\",\n    post: true\n});\napp.use(autoresponse);\n\nvar serveStatic = require(\"serve-static\");\napp.use(serveStatic(\"./webroot\"));\n```\n\n## Using in webpack-dev-server\n\n[webpack-dev-server](https://github.com/webpack/webpack-dev-server) is developed based on `express`, so `autoresponse` can as a middleware served it using `setup` option.\n\n```javascript\nvar compiler = Webpack(webpackConfig);\nvar server = new WebpackDevServer(compiler, {\n    // install middlewares，if your webpack version is less than 3.0.0, using `setup` option instead of `before` option\n    before: function(app) {\n        var autoresponse = require(\"autoresponse\");\n        app.use(\n            autoresponse({\n                logLevel: \"debug\",\n                root: projectRootPath, // you can specify the project root path\n                post: true, // mock all post request\n                patch: true // mock all patch request\n            })\n        );\n    }\n});\n\nserver.listen(8888, function() {\n    console.log(\"Starting server on port 8888...\");\n});\n```\n\n## Using in edp-webserver\n\nIf you use [EDP](https://github.com/ecomfe/edp) solution, you can also use `autoresponse` middleware in [edp-webserver](https://github.com/ecomfe/edp-webserver) to mock the http request.\n\n```javascript\nexports.getLocations = function() {\n    return [\n        {\n            location: \"/\",\n            handler: home(\"index.html\")\n        },\n        {\n            location: /\\.html\\b.*$/,\n            handler: [file()]\n        },\n        // add autoresposne mock handler\n        require(\"autoresponse\")(\"edp\", { watch: true, logLevel: \"info\" }),\n        {\n            location: /^.*$/,\n            handler: [file(), proxyNoneExists()]\n        }\n    ];\n};\n```\n\n## Using mock config file \u003ca name=\"config-file\"\u003e\u003c/a\u003e\n\nCreate `autoresponse` middleware:\n\n```javascript\nvar autoresponse = require(\"autoresponse\")({\n    // specify whether need auto reload config file when config file change\n    watch: true\n});\n```\n\nCreate `autoresponse-config.js` file in your web document root, the config file content like the following:\n\n```javascript\nmodule.exports = {\n    // The response directory to mock, by default is `mock`\n    responseDir: \"./mock\",\n\n    /**\n     * configure the `get` request, determine the request path and the file to be mocked.\n     * You can also configure the `post` request and `query` params to mock.\n     * More information, please refer to examples.\n     *\n     * @type {boolean|Array}\n     */\n    get: [\n        {\n            match: \"/b.html\",\n            mock: \"c.html\"\n        },\n        {\n            match: \"/account/getUserInfo\", // also support regex and function\n            mock: {\n                proxy: \"localhost:9090\" // use proxy\n            }\n        },\n        {\n            // default mock file: \u003cresponseDir\u003e/user/profile.js\n            // it'will be processed as a node module by builtin js-processor\n            match: \"/user/profile\"\n        },\n        {\n            match: \"/data/list\",\n            mock: \"data/list.json\"\n        },\n        {\n            match: \"/php\",\n            mock: {\n                path: \"/data/test.php\" // rewrite request path\n            }\n        },\n        {\n            match: \"/a/b\",\n            mock: \"a/b.php\" // mock with php file which is processed by php processor\n        },\n        \"/account/getUserInfo\", // specify the match path\n        function(reqPath, context) {\n            // using function to determine which request to mock\n            return {\n                match: \"a/b\"\n            };\n        }\n    ]\n};\n```\n\n## Using smarty processor\n\nConvert `json` data to `html` or `html segment` using `smarty` template engine.\n\n**prepare：**\n\n-   install php-cgi\n\n    -   [for mac](https://gist.github.com/xiangshouding/9359739)\n    -   [for windows](https://gist.github.com/lily-zhangying/9295c5221fa29d429d52)\n\n-   processor configure\n\n```javascript\n// add this config to autoresponse\nprocessor: {\n    smarty: {\n        // specify the initialize configure file, the file path is relative to `responseDir`\n        // the file content you can refer below\n        initerFile: './initer.php',\n\n        // you also can specify your php-cgi path here, default using `php-cgi`\n        php: {bin: '\u003cphp-cgi path\u003e'}\n    }\n}\n```\n\n```php\n\u003c?php\n\n// ============== initer.php ================\n\nerror_reporting(0);\nini_set('error_reporting', E_ALL \u0026 ~E_NOTICE);\n\n$project_root = dirname(dirname(__FILE__));\n\nrequire dirname($project_root) . '/libs/Smarty.class.php';\n\n// initialize the smarty variable\n$smarty = new Smarty;\n\n$smarty-\u003eforce_compile = true;\n$smarty-\u003edebugging = false;\n$smarty-\u003ecaching = false;\n\n// specify the delimiter chararter\n$smarty-\u003eleft_delimiter = '{';\n$smarty-\u003eright_delimiter = '}';\n\n// setting the template directory and output directory for compilation\n$smarty-\u003esetTemplateDir($project_root . '/templates/');\n$smarty-\u003esetCompileDir($project_root . '/templates_c/');\n```\n\n-   write smarty json data using js processor\n\n    -   output html document\n\n        ```javascript\n        module.exports = function(path, queryParam, postParam) {\n            return {\n                // of course, you can specify the delay time with a random value between 0 and 100\n                _timeout: \"0,100\",\n\n                // if you wanna simulate the special status, you can use this\n                _status: 404,\n\n                // tell autoresponse that the json data will be processed by smarty processor\n                _process: \"smarty\",\n\n                // the smarty template name will be rendered\n                _tpl: \"a/b.tpl\",\n\n                // define the template data to be applied to smarty template file\n                _data: {\n                    extData: [],\n                    tplData: {}\n                }\n            };\n        };\n        ```\n\n    -   output json with smarty render result\n\n\n        ```javascript\n        module.exports = function (path, queryParam, postParam) {\n            return {\n                // the json data will be processed by smarty processor\n                _process: 'smarty',\n\n                filters: [],\n\n                // the smarty render result will be replaced as the value of `filterTpl`\n                filterTpl: {\n                     // the smarty template name will be rendered\n                     _tpl: 'filter.tpl',\n                     // define the template data to be applied to smarty template file\n                     _data: {\n                         extData: [],\n                         tplData: {}\n                     }\n                }\n            };\n        };\n        ```\n\n## Using mock helper method \u003ca name=\"helper\"\u003e\u003c/a\u003e\n\nBy default, if you use js file to mock, you can access `mock` global variable in your mock file.\n\nThe following methods are provided by default:\n\n-   `mock._`: [lodash](https://lodash.com/docs) variable\n\n-   `mock.m`: [dayjs](https://github.com/iamkun/dayjs) variable，using [moment](http://momentjs.com/docs/) before the `0.3.0` version\n\n-   `mock.fake(format, locale)`: the encapsulation of [faker](https://github.com/Marak/faker.js/)\n\n    ```javascript\n    // more api and variable name, please refer faker api docs\n    mock.fake(\"{{name.firstName}}-{{name.lastName}}\");\n    ```\n\n-   `mock.fakeCN(format)`: generate chinese locale random information\n\n-   `mock.fakeEN(format)`: is equivalent to `mock.fake(format)`, generate english locale random information\n\n-   `mock.faker(locale)`: get `faker` instance with the specified locale, the locale argument is default english\n\nMore details, please refer to the [autoresponse-config.js](https://github.com/wuhy/autoresponse/blob/master/lib/autoresponse-config.js).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwuhy%2Fautoresponse","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwuhy%2Fautoresponse","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwuhy%2Fautoresponse/lists"}