使用json-server模拟数据

使用场景

  • 工作中,在进行前端开发时,如果后端还没有做好准备,很多时候,我们并不想使用简单的静态数据,这个时候,我们就可以使用json-server来完成模拟请求以及返回数据的过程。

  • json-server 是一个 Node 模块,运行 Express 服务器,你可以指定一个 json 文件作为 api 的数据源,简单来讲就是可以用来模拟接口数据。

  • 安装

    • 使用npm全局安装:npm install -g json-server

    • 或者使用yarn全局安装:yarn global add json-server

使用

  • 在你的项目根目录【src】下新建一个 db.json 文件
  • 然后写入以下内容
  {
    "posts": [
      {
        "positionId": 1,
        "title": "bbb",
        "author": "lucy",
        "info":{
          "age":18,
          "sex":"man"
        }
      },
      {
        "positionId": 2,
        "title": "yyy",
        "author": "nike"
      },
      {
        "positionId": 3,
        "title": "aaa",
        "author": "json"
      }
    ],
    "comments": [
      {
        "id": 1,
        "body": "some comment",
        "postId": 1
      }
    ],
    "profile": {
      "name": "typicode"
    }
  }

启动服务

  • 控制台输入json-server json文件路径,启动 Json 服务,把这个文件返回的数据托管成web服务

json-server 常用的一些配置项

配置项 简写 类型 描述
–watch -w [Boolean] 是否监视文件,自动刷新数据
–port -p [Number] 设置端口号,默认为3000
–host -H [String] 设置域,默认为"localhost"
–routes -r [String] 指定路由文件
–static -s 设置静态资源目录,可以用来访问图片
–id -i [String] 设置数据的key值,默认为“id",即默认拿取key为id的value值
posted @ 2022-08-05 15:15  小学生学Web前端  阅读(259)  评论(0)    收藏  举报