Json-Server使用

Json-Server使用教程

Json-Server 是一个 Node 模块,运行 Express 服务器,我们可以指定一个 json 文件作为 api 的数据源。

Json-Server 可以直接把一个 json 文件托管成一个具备全 RESTful 风格的 API,并支持跨域、jsonp、路由订制、数据快照保存等功能的 web 服务器。

Json-Server启动详解

语法

json-server [options] <source>

参数

参数 描述
json-server 安装好的二进制进程。
options 启动的可选参数。
source 数据文件的地址,可以是 json 文件或者 js 文件。

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启动实例

不监听文件变化

json-server --port 53000 db.json

如果启动时,不使用 --watch 参数,那么即使 db.json 文件发生变化,json-server 返回的还是原数据。

使用Json文件

json-server --watch --port 53000 db.json

将 db.json 文件托管成一个 web 服务,并指定监听的端口为 53000。

使用 Js 文件

json-server --watch --port 53000 db.js

将 db.js 文件返回的数据托管成 web 服务。

Json-Server使用总结

Json-Server 的数据文件,可以是 json 文件或者 js 文件。数据文件如果是 js 文件,那么是将 js 文件返回的数据托管成 web 服务。

Json-Server 启动时,如果不使用 --watch 参数,那么即使数据文件发生变化,Json-Server 返回的还是原数据。