Json-Server的使用

  1. 准备后台测试数据(db.json):

    {
      "items": [
        {
          "id": 1,
          "title": "Blue Socks",
          "price": 2.99,
          "originalPrice": 3.99,
          "rating": 4.3,
          "img": "http://lorempixel.com/400/400/abstract/1/"
        },
        {
          "id": 2,
          "title": "Green Socks",
          "price": 3.99,
          "rating": 3.9,
          "img": "http://lorempixel.com/400/400/abstract/2/"
        },
        {
          "id": 3,
          "title": "Red Socks",
          "price": 3.99,
          "rating": 4,
          "img": "http://lorempixel.com/400/400/abstract/3/"
        },
        {
          "id": 4,
          "title": "Blue Shirt",
          "price": 16.99,
          "originalPrice": 19.99,
          "rating": 3.4,
          "img": "http://lorempixel.com/400/400/abstract/4/"
        },
        {
          "id": 5,
          "title": "Green Shirt",
          "price": 19.99,
          "rating": 4.2,
          "img": "http://lorempixel.com/400/400/abstract/5/"
        },
        {
          "id": 6,
          "title": "Red Shirt",
          "price": 19.99,
          "rating": 4.1,
          "img": "http://lorempixel.com/400/400/abstract/6/"
        },
        {
          "id": 7,
          "title": "Grey Shirt",
          "price": 6.99,
          "originalPrice": 19.99,
          "rating": 2.6,
          "img": "http://lorempixel.com/400/400/abstract/7/"
        },
        {
          "id": 8,
          "title": "Black Backpack",
          "price": 39.99,
          "rating": 4.7,
          "img": "http://lorempixel.com/400/400/abstract/8/"
        }
      ],
      "comments": [
        {
          "id": 1,
          "text": "This is awesome!",
          "itemId": 1
        }
      ]
    }
    
  2. 安装依赖:

    // 由于json-server只是用来测试的,所以我们就把它安装到开发环境里就好了,也就是-D
    cnpm install json-server -D
    
  3. 在package.json里添加相应脚本(注:这里的db.json和package.json位于同级目录,也就是项目的根目录下):

    "scripts": {
      "db": "json-server --watch db.json",
      ......
    },
    
  4. 此时我们就可以通过命令启动了:

    npm run db
    
  5. 运行完后,会显示如下,你可以通过这些url发送请求:

  6. 具体如何使用可以看文档,文档已经很详细了,这里就没必要重复造轮子了:

    官方文档(英文):https://www.npmjs.com/package/json-server
    中文博客(写的不错,而且还是中文):https://www.jianshu.com/p/bdbbd3314cf3
    

你可能感兴趣的:(Json-Server的使用)