json-server 使用
1.概述
JSON-Server 是一个 Node 模块,运行 Express 服务器,你可以指定一个 json 文件作为 api 的数据源。
json-server
可以直接把一个json
文件托管成一个具备全RESTful
风格的API
,并支持跨域、jsonp
、路由订制、数据快照保存等功能的 web 服务器。
2.安装已经启动
-
npm install -g json-server
-
npm init, 新建 server/db.json
{ "posts": [ {"id": 1, "title": "json-serve", "author": "typicode" } ], "comments": [ {"id": 1, "body": "some comment", "postId": 1} ], "profile": {"name": "typicode"} }
3.package.json
"json:server": "json-server --watch db.json"
- npm run json:server, 默认启动端口是3000.也可以配置端口,
json-server --watch --port 53000 db.json
- 启动成功后的结果
3. json-server相关启动参数
参数 简写 默认值 说明 –config -c 指定配置文件 [默认值: “json-server.json”] –port -p 设置端口 [默认值: 3000] Number –host -H 设置域 [默认值: “0.0.0.0”] String –watch -w Watch file(s) 是否监听 –routes -r 指定自定义路由 –middlewares -m 指定中间件 files [数组] –static -s Set static files directory 静态目录,类比:express的静态目录 –readonly –ro Allow only GET requests [布尔] –nocors –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”] –foreignKeySuffix – fks Set foreign key suffix (e.g. _id as in post_id) [默认值: “Id”] –help -h 显示帮助信息 [布尔] –version -v 显示版本号 [布尔]
$ json-server --watch -c ./jsonserver.json
$ json-server --watch app.js
$ json-server db.json
json-server --watch -port 8888 db.json