json-server 模拟API

Getting started

  • Create a db.json file with some data(创建de.json)
{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}
  • Start JSON Server
json-server --watch db.json
{ "id": 1, "title": "json-server", "author": "typicode" }
  • If you make POST, PUT, PATCH or DELETE requests, changes will be automatically and safely saved to db.json using lowdb.(使用 lowdb 数据库保存被修改的JSON数据)
  • Id values are not mutable.(id不可修改)
    • Any id value in the body of your PUT or PATCH request will be ignored. (被忽略)
    • Only a value set in a POST request will be respected, but only if not already taken.(未引用可被POST请求设置?)
  • A POST, PUT or PATCH request should include a Content-Type: application/json header to use the JSON in the request body. (修改请求传输 JSON body 时需要设置头部 Content-Type: application/json)
    • Otherwise it will result in a 200 OK but without changes being made to the data.(否则将返回200但是未修改数据)

——————————————————————————————————————————————————————————————

Routes

Plural routes

  • 请求数组posts中id=1的对象
GET    /posts/1

Singular routes

GET    /profile
POST   /profile
PUT    /profile
PATCH  /profile

Filter

  • 带查询条件,查询posts数组中title=json-server且author=typicode的项,返回数组集合
http://localhost:3000/posts?title=json-server&author=typicode
  • 查询posts数组中id=1或id=2的项,返回数组集合
http://localhost:3000/posts?id=1&id=2
  • Use . to access deep properties(使用 . 访问深层属性,如果没有该深层属性将会返回整个数组)
http://localhost:3000/posts?author.name=typicode

{
  "posts": [
    {
      "id": 1,
      "title": "json-server1",
      "author": "typicode1"
    },
    {
      "id": 2,
      "title": "json-server2",
      "author": {
        "name": "typicode"
      }
    }
  ]
}

Paginate

  • 返回分页数据,每页1条,第2页。默认每页10条
http://localhost:3000/posts?_page=2&_limit=1
  • In the Link header you'll get first,prev,next and last links.

Sort

  • 根据title和author排序,优先满足title。默认升序
http://localhost:3000/posts?_sort=title,author
  • ?
GET /posts?_sort=views&_order=asc
  • ?如何降序

Slice

  • 返回posts数组中下标为2-3的数组
http://localhost:3000/posts?_start=2&_end=4
  • posts数组中从下标为1的项开始,返回10项
http://localhost:3000/posts?_start=1&_limit=10

Operators

  • 返回posts数组中,title大于等于1,小于等于3的项。返回数组集合
http://localhost:3000/posts?title_gte=1&title_lte=3
  • 返回posts数组中,title不等于1的项。返回数组集合
http://localhost:3000/posts?title_ne=1
  • 返回posts数组中,title包含1的项。返回数组结合。支持正则表达式
http://localhost:3000/posts?title_like=1

http://localhost:3000/posts?title_like=^\d
  • 在posts中每一项的属性中查询含有a的项。返回数组集合
http://localhost:3000/posts?q=a

Relationships

  • 获取posta数组,且关联comments中。该例中通过 comments.postId 和 posts.id 相关联
http://localhost:3000/posts?_embed=comments

{
  "posts": [
    {
      "id": 1,
      "title": "json-server",
      "author": "typicode"
    }
  ],
  "comments": [
    {
      "id": 1,
      "body": "some comment",
      "postId": 1
    },
    {
      "id": 2,
      "body": "some comment",
      "postId": 2
    }
  ],
}

// 返回
[
  {
    "id": 1,
    "title": "json-server",
    "author": "typicode",
    "comments": [
      {
        "id": 1,
        "body": "some comment",
        "postId": 1
      }
    ]
  }
]
  • 获取 comments 数组,且包含父资源。(注意这里是 post 不是 posts)
http://localhost:3000/comments?_expand=post

// db.json同上

// 返回
[
  {
    "id": 1,
    "body": "some comment",
    "postId": 1,
    "post": {
      "id": 1,
      "title": "json-server",
      "author": "typicode"
    }
  },
  {
    "id": 2,
    "body": "some comment",
    "postId": 2
  }
]
  • 获取 posts 下 id 等于 1 的对象下嵌套的 comments 中的项,返回数组集合。(by default one level, add custom routes for more) 只支持一层嵌套
http://localhost:3000/posts/1/comments

// 返回
[
  {
    "id": 1,
    "body": "some comment",
    "postId": 1
  }
]

Database

  • 返回整个 db.json 对象
http://localhost:3000/db

Homepage

  • Returns default index file or serves ./public directory(返回服务首页)
http://localhost:3000/

——————————————————————————————————————————————————————————————

Extras

Static file server

  • 可以作为一个静态服务器,--static指定静态服务器相对于 package.json 的地址,默认为./public
json-server --watch json-server/db.json --static ./json-server/public

// 获取 public 中的 cs.js 文件
http://localhost:3000/cs.js

Alternative port

  • 修改服务器监听端口
json-server --watch db.json --port 3004

Access from anywhere

  • You can access your fake API from anywhere using CORS and JSONP.(支持 CORS 和 JSONP)

Remote schema

  • You can load remote schemas.(支持加载远程的配置,支持加载文件夹?)
json-server http://example.com/file.json
json-server http://jsonplaceholder.typicode.com/db

Generate random data

  • 可以使用编程的方式创建数据
module.exports = () => {
  const data = { users: [] }
  // Create 1000 users
  for (let i = 0; i < 1000; i++) {
    data.users.push({ id: i, name: `user${i}` })
  }
  return data
}

json-server --watch json-server/db.js

http://localhost:3000/users

HTTPS

  • 使用 https ,可以参考 https://github.com/typicode/hotel

Add custom routes

  • 自定义资源访问路由
json-server --watch json-server/db.json --routes ./json-server/routes.json
  • 路由的设置方式
{
  "/api/*": "/$1",
  "/:resource/:id/show": "/:resource/:id",
  "/posts/:category": "/posts?category=:category",
  "/articles\\?id=:id": "/posts/:id"
}

// 匹配
/api/posts # → /posts
/api/posts/1  # → /posts/1

/posts/1/show # → /posts/1
/posts/javascript # → /posts?category=javascript
/articles?id=1 # → /posts/1

Add middlewares

  • You can add your middlewares from the CLI using --middlewares option:(添加中间层,请求响应拦截器,支持链式)
// hello.js
module.exports = (req, res, next) => {
  res.header('X-Hello', 'World')
  next()
}

json-server db.json --middlewares ./hello.js
json-server db.json --middlewares ./first.js ./second.js

CLI usage

json-server [options] <source>

Options:
  --config, -c       Path to config file           [default: "json-server.json"]
  --port, -p         Set port                                    [default: 3000]
  --host, -H         Set host                             [default: "localhost"]
  --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(只允许 get 请求)                           [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)(数据库ID对应的字段名)         [default: "id"]
  --foreignKeySuffix, --fks  Set foreign key suffix, (e.g. _id as in post_id)(设置外键后缀)         [default: "Id"]
  --quiet, -q        Suppress log messages from output(禁止输出日志)                 [boolean]
  --help, -h         Show help                                         [boolean]
  --version, -v      Show version number                               [boolean]
  • json-server.json 文件
{
  "port": 3000
}

Module(以下待补充)

Simple example

Custom routes example

Access control example

Custom output example

Rewriter example

Mounting JSON Server on another endpoint example

API

Deployment

——————————————————————————————————————————————————————————————

Video

Articles

Third-party tools

——————————————————————————————————————————————————————————————

License

转载于:https://www.cnblogs.com/qq3279338858/p/11576787.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值