1. 程式人生 > >使用json-server搭建虛擬後臺伺服器,並完成資料的增刪改查

使用json-server搭建虛擬後臺伺服器,並完成資料的增刪改查

在很多前後端分離的專案中,前後端同時開工,當前段專案已完成部分後,就需要獲取資料來做部分除錯,但是這個時候後臺伺服器往往還沒有完成,這個時候就需要我們自己搭建一個虛擬的後臺伺服器,無意中發現一款好用的"神器",我把自己搭建伺服器和進行一些增刪改查操作的具體步驟記錄了下來,以供大家參考;

第一步 利用json-server搭建虛擬伺服器

1.新建一個資料夾jsonServer,並在根目錄下生成package.json檔案;

package.json檔案可通過以下命令來生成

npm init

2.安裝json-server

npm install json-server -g

執行如下命令,檢查json-server是否安裝成功

json-server -h

如果安裝成功,控制檯會出現如下:

E:\JsonServer>json-server -h
index.js [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                   [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"]
  --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]

Examples:
  index.js db.json
  index.js file.js
  index.js http://example.com/db.json

https://github.com/typicode/json-server

3.在根目錄下建立db.json檔案,此檔案儲存前端測試需要的資料檔案;

我檔案內只儲存了部分測試資料,如下;

{
  "users": [
    {
      "id": 6985851,
      "username": "lnx132133",
      "phone": "13212345678",
      "mail": "[email protected]",
      "gender": "女",
      "department": "研發三部",
      "avatar": "../../../static/img/avatar.jpg",
      "character": "普通使用者",
      "remarks": "張九"
    },
    {
      "id": 6985852,
      "username": "dsfa132133",
      "phone": "13312345678",
      "mail": "
[email protected]
", "gender": "男", "department": "研發二部", "avatar": "../../../static/img/avatar.jpg", "character": "管理員", "remarks": "李明" }, { "id": 6985424, "username": "dsdfa132133", "phone": "13412345678", "mail": "[email protected]", "gender": "男", "department": "研發二部", "avatar": "../../../static/img/avatar.jpg", "character": "管理員", "remarks": "劉震" }, { "id": 6985754, "username": "dsfg132133", "phone": "13512345678", "mail": "[email protected]", "gender": "女", "department": "客服部", "avatar": "../../../static/img/avatar.jpg", "character": "管理員", "remarks": "徐梅" }, { "id": 6985132, "username": "dsfa132133", "phone": "13612345678", "mail": "[email protected]", "gender": "男", "department": "市場部", "avatar": "../../../static/img/avatar.jpg", "character": "管理員", "remarks": "張強" }, { "id": 6985715, "username": "dsfa132133", "phone": "13712345678", "mail": "[email protected]", "gender": "男", "department": "研發二部", "avatar": "../../../static/img/avatar.jpg", "character": "管理員", "remarks": "宋傑" }, { "id": 6985741, "username": "dsfa132133", "phone": "13812345678", "mail": "[email protected]", "gender": "男", "department": "研發二部", "avatar": "../../../static/img/avatar.jpg", "character": "普通使用者", "remarks": "何宇" }, { "id": 69858965, "username": "dsfa132133", "phone": "13912345678", "mail": "[email protected]", "gender": "男", "department": "研發二部", "avatar": "../../../static/img/avatar.jpg", "character": "普通使用者", "remarks": "強東" }, { "id": 6988959, "username": "lnx132199", "phone": "13212345678", "mail": "[email protected]", "gender": "男", "department": "研發一部", "avatar": "../../../static/img/avatar.jpg", "character": "普通使用者", "remarks": "張八" }, { "id": "6988960", "username": "lnx132199", "phone": "13212345678", "mail": "[email protected]", "gender": "男", "department": "研發一部", "avatar": "../../../static/img/avatar.jpg", "character": "普通使用者", "remarks": "張八" } ] }

4.啟動josn-server伺服器

在控制檯執行如下命令

json-server --watch db.json

執行成功後的結果

  \{^_^}/ hi!

  Loading db.json
  Done

  Resources
  http://localhost:3000/users

  Home
  http://localhost:3000

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

第二步 對資料進行增刪改查操作

json-server支援的操作方法如下

GET /users--------------------------------------------------------------------------------------------------------------------------獲取列表
GET /users/id ------------------------------------------------------------------------------------------------------------------------獲取指定id的資料
POST /users -------------------------------------------------------------------------------------------------------------------------新增一個數據物件
PUT /users/id------------------------------------------------------------------------------------------------------------------------- 更新指定id物件的資料
DELETE /users/id -------------------------------------------------------------------------------------------------------------------刪除指定id的資料

注:篇幅限制,在此就不一一介紹,需要詳細了點這裡→https://www.npmjs.com/package/json-server

1.查詢資料---GET /users

        //請求使用者資料
        $.ajax({
            type:"GET",
            url:"http://localhost:3000/users",
            dataType:"json",
            success:function (data) {
                console.log(data);
            },
            error:function (err) {
                console.error(err);
            }
        });

輸出結果:

2.獲取指定id的資料---GET /users/id

        //獲取指定使用者
        $("#getUser").click(function(){
            $.ajax({
                type:"GET",
                url:"http://localhost:3000/users/6985715",
                dataType:"json",
                success:function(data){
                    console.log(data);
                },
                error:function(err){
                    console.error(err)
                }
            })
        });

輸出結果:

3.新增使用者資料-------POST /users

        //增加使用者資料
        $("#addUser").click(function(){
            var newUser={
                "id": 6988960,
                "username": "lnx132199",
                "phone": "13212345678",
                "mail": "[email protected]",
                "gender": "男",
                "department": "研發一部",
                "avatar": "../../../static/img/avatar.jpg",
                "character": "普通使用者",
                "remarks": "張八"
            };
            $.ajax({
                type:"POST",
                url:"http://localhost:3000/users",
                data:newUser,
                success:function(data){
                    console.log("新增成功");
                },
                error:function(err){
                    console.error(err)
                }
            })
        });

結果:

檢視db.json檔案中已經有了新增的資料

4.更改指定物件資料------PUT /users/id

        //修改使用者資料
        $("#updateUser").click(function(){
            var updateuser={
                "id": 6985851,
                "username": "lnx132133",
                "phone": "13212345678",
                "mail": "[email protected]",
                "gender": "男",
                "department": "研發四部",
                "avatar": "../../../static/img/avatar.jpg",
                "character": "普通使用者",
                "remarks": "劉工"
            };
            $.ajax({
                type:"PUT",
                url:"http://localhost:3000/users/6985851",
                data:updateuser,
                success:function(data){
                    console.log(data)
                },
                error:function(err){
                    console.error(err)
                }
            })
        });

控制檯輸出結果:

檢視db.json檔案,指定使用者的資訊也已經更改過來了;

5.刪除指定使用者----------DELETE /users/id

        //刪除使用者
        $("#delUser").click(function(){
            var delUserId=6988960;
            $.ajax({
                type:"DELETE",
                url:"http://localhost:3000/users/"+delUserId,
                dataType:"json",
                success:function(data){
                    console.log(data)
                },
                error:function(err){
                    console.error(err)
                }
            })
        })

執行完刪除指定使用者指令後,會返回一個空物件;

檢視db.json檔案發現指定id 的物件已經刪除

以上就是使用json-server做資料虛擬操作的全部步驟,我最近還在更加深入的學習,學習完成後再進行更新;