Skip to content

使用json-server轻松模拟rest api #168

@GuoYongfeng

Description

@GuoYongfeng

使用 json-server 轻松模拟 rest api

前端进行开发的时候经常需要模拟和后端约定的数据格式进行并行开发,这样可以有效的提高开发效率。无论是借助 webpack 等工具内置的 node 服务实现还是使用第三方独立的模块,大家都在聚焦于如何可以轻松高效的实现前端数据模拟。

接下来为大家介绍使用 json server 这样一个 mock 工具,因为它足够简单,写少量数据,即可使用。也因为它足够强大,支持CORS和JSONP跨域请求,支持GET, POST, PUT, PATCH 和 DELETE 方法,更提供了一系列的查询方法,如limit,order等。

安装

$ sudo npm install json-server -g
$ json-server -h

可以看到具体的帮助信息

Options:
  --config, -c       Path to config file    [default: "json-server.json"]
  --port, -p         Set port                             [default: 3000]
  --host, -H         Set host                        [default: "0.0.0.0"]
  --watch, -w        Watch file(s)                              [boolean]
  --routes, -r       Path to routes file
  --middlewares, -m  Paths to middleware files                    [array]
  --static, -s       Set static files directory
  --read-only, --ro  Allow only GET requests                    [boolean]
  --no-cors, --nc    Disable Cross-Origin Resource Sharing      [boolean]

  --no-gzip, --ng    Disable GZIP Content-Encoding              [boolean]
  --snapshots, -S    Set snapshots directory               [default: "."]
  --delay, -d        Add delay to responses (ms)
  --id, -i           Set database id property (e.g. _id)  [default: "id"]
  --quiet, -q        Suppress log messages from output          [boolean]
  --help, -h         Show help                                  [boolean]
  --version, -v      Show version number                        [boolean]

Examples:
  /usr/local/bin/json-server db.json
  /usr/local/bin/json-server file.js
  /usr/local/bin/json-server
  http://example.com/db.json

快速上手示例

mkdir mock-data 
cd mock-data
touch db.json

db.json 写上简单的 json 数据

{
	"data": {
		"name": "GuoYongfeng",
		"id": "0000057933"
	}
}

注意,data 字段的值必须是 array 或是 object

执行

$ json-server -p 3000 db.json --watch

其中 -p 指定端口,watch为监听 json 文件改动。

这时候出现以下信息:

  \{^_^}/ hi!

  Loading db.json
  Done

  Resources
  http://localhost:3000/data


  Home
  http://localhost:3000

  Type s + enter at any time to create a snapshot of the database
  Watching...

GET / 200 8.823 ms - -
GET /stylesheets/style.css 200 4.505 ms - 152
GET /images/json.png 200 4.014 ms - 278
GET /db 200 3.603 ms - 69

访问 http://localhost:3000/data 将可以看到模拟的数据。

学习资源推荐

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions