json-server+mockjs 模擬REST接口


前言:

項目開發中,影響項目進程的常常是由於在前后端數據交互的開發流程中停滯,前端完成靜態頁面的開發后,后端遲遲未給到接口。而現在,我們就可以通過根據后端接口字段,建立一個REST風格的API接口,進而實現mock數據實現前端的獨立開發。

json-server

通過json-server完成mock數據

GitHub介紹:Get a full fake REST API with zero coding in less than 30 seconds (seriously)

      Created with <3 for front-end developers who need a quick back-end for prototyping and mocking.

GitHub鏈接:https://github.com/typicode/json-server

1.安裝

cmd命令行安裝json-server

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"]

  --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]

2.小試身手

新建db.json文件

運行cmd命令行

json-server --watch db.json

若打印出如下表 

則運行成功,因json-server默認監聽的3000端口,直接訪問地址:http://localhost:3000/posts可得結果

注:json-server里面的id是不可變的。用來標識每一條數據,這就好比該json文件時一個數據庫,根屬性名對應一張張的表,id是表里面的primary key。因此,如果如果你用put方法推入一條帶有id的數據,是會被忽略的。

3.接口及參數

json-server支持CORS和JSONP跨域請求,支持GET, POST, PUT, PATCH 和 DELETE 方法,也提供了一系列的參數查詢方法。

3.1簡單應用

啟動服務:json-server --watch db.json,通過jquery的ajax我們可以簡單的應用

3.2接口應用
3.2.1使用get接口查詢數據

通過地址:localhost:3000/posts?id=2,這種get方式完成參數請求

3.2.2使用post接口新增數據
 1 $.ajax({
 2             url:'http://localhost:3000/posts',
 3             dataType:'json',
 4             type:'post',
 5             data:{
 6                 "id":4,
 7                 "title":"css",
 8                 "author":"authorX"
 9             },
10             success:(data)=>{
11                 console.log(data);
12             },
13             error:(err)=>{
14                 console.log(err);
15             }
16         })

通過post方式,我們可以在db.json后面追加數據

 3.2.3使用put接口修改數據

通過修改type類型為put,對db.json中id=2的數據進行修改

 1 $.ajax({
 2             url:'http://localhost:3000/posts/2',
 3             dataType:'json',
 4             type:'put',
 5             data:{
 6                 "title":"css3",
 7                 "author":"authorX"
 8             },
 9             success:(data)=>{
10                 console.log(data);
11             },
12             error:(err)=>{
13                 console.log(err);
14             }
15         })

 

3.3參數應用
3.3.1 分頁【關鍵字:_page】

應用:http://localhost:3000/posts?_page=1

 3.3.2 排序【關鍵字:_sort,_order】

_sort后面為要分類的鍵名

應用:http://localhost:3000/posts?_sort=author

_order為排序的方式。DESC(倒序),ASC(順序)

應用:http://localhost:3000/posts?_sort=author&_order=DESC

3.3.3 切分【關鍵字:_start,_end,_limit】

類似於js里面的slice函數。slice(_start,_end),從數據里面取出數據。數據不包括_end,
_limit可以和_start配合,表示從_start位置開始_limit條數據被取出來。

應用:http://localhost:3000/posts?_start=1&_limit=3

3.3.4 操作【關鍵字:_gte,_lte,_ne,[key]_like】

_gte:大於或等於,_lte:小於或等於,_ne:不等於,[key]_like:模糊搜索

應用:http://localhost:3000/posts?author_like=author

3.3.5 全局搜索【關鍵字:q】

q為數據中全局搜索傳入的參數

應用:http://localhost:3000/posts?q=json

3.3.6 字段擴展【關鍵字:_embed,_expand】

_embed:擴展子數據字段

_expand:擴展父數據字段

應用:http://localhost:3000/posts/2?_embed=search

 

4 結合mock.js生成隨機數據

由於通過json-server結合js動態生成的json文件略顯單一並且對於大量的數據顯得不太適合

如下例子:

 1 module.exports=()=>{
 2     const data={users:[]}
 3     for(let i=0;i<1000;i++){
 4         data.users.push({
 5             id:i,
 6             name:`user${i}`
 7         })
 8     }
 9     return data
10 };

執行json-server index,js

於是我們借助mockjs生成更加符合實際測試的數據。

不少人認識到mockjs也是一個獨立的mock servr,為啥不單獨使用mockjs而結合json-server使用呢

把mockjs單獨作為數據構造器使用是由於mockjs:

不能跨域使用;與某些框架的路由邏輯處理存在沖突;無法定義一些復雜的數據結構等。

4.1 結合mockjs構造數據接口
4.1.1 命令行安裝mockjs
npm install mockjs --save

mock新聞列表數據:news.js

 1 let Mock=require('mockjs');
 2 let Random=Mock.Random;
 3 
 4 module.exports=()=>{
 5     let data={
 6         news:[]
 7     };
 8 
 9     let images=[1,2,3].map(x=>Random.image('120x60',Random.color(),Random.word(2,6)));
10 
11     for(let i=0;i<100;i++){
12         let content=Random.cparagraph(0,10);
13 
14         data.news.push({
15             id:i,
16             title:Random.cword(8,20),
17             desc:content.substr(0,40),
18             tag:Random.cword(2,6),
19             views:Random.integer(100,5000),
20             images:images.slice(0,Random.integer(1,3))
21         })
22     }
23     return data
24 }
4.1.2 運行
json-server news.js

部分截圖:

至此,我們就可以通過json-server+mockjs完成完成的數據接口模擬。

 

更多參考:

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

    mockjs:https://github.com/nuysoft/Mock/wiki/Getting-Started

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM