对比过多种mock工具后,我最终选择了使用 json server 作为工具,因为它足够简单,写少量数据,即可使用。 也因为它足够强大,支持CORS和JSONP跨域请求,支持GET, POST, PUT, PATCH 和 DELETE 方法,更提供了一系列的查询方法,如limit,order等。下面我将详细介绍 json server 的使用。
安装
首先你的电脑中需要安装nodejs,建议使用最新版本。然后全局安装json server.
npm install json-server -g
使用linux和macOS的电脑需要加上sudo
sudo npm install json-server -g
安装完成后可以用 json-server -h 命令检查是否安装成功,成功后会出现
json-server [options]
选项:
--config, -c Path to config file [默认值: "json-server.json"]
--port, -p Set port [默认值: 3000]
--host, -H Set host [默认值: "0.0.0.0"]
--watch, -w Watch file(s) [布尔]
--routes, -r Path to routes file
--static, -s Set static files directory
--read-only, --ro Allow only GET requests [布尔]
--no-cors, --nc Disable Cross-Origin Resource Sharing [布尔]
--no-gzip, --ng Disable GZIP Content-Encoding [布尔]
--snapshots, -S Set snapshots directory [默认值: "."]
--delay, -d Add delay to responses (ms)
--id, -i Set database id property (e.g. _id) [默认值: "id"]
--quiet, -q Suppress log messages from output [布尔]
--help, -h 显示帮助信息 [布尔]
--version, -v 显示版本号 [布尔]
示例:
json-server db.json
json-server file.js
json-server http://example.com/db.json
https://github.com/typicode/json-server