json-server就是一個在前端本地運行,專門模擬后端接口地址的可以存儲json數據的簡易版server。
為什么使用json-server?
這里就是我們所要說的前后端分離方式開發了。前后端是完全獨立的兩個項目,前后端兩個項目是並行開發,也就是說前端項目開發時,后端接口還沒開發好呢,此時就需要前端開發人員要用最簡單的方法,模擬出后端接口地址,來保證前端項目的開發進度。。。。
安裝json-server:
npm install -g json-server
如何使用json-server?
- 定義一個db,json文件(這里是練習文件)
鏈接:https://pan.baidu.com/s/11lQFJp62h_wmyKZHaiMFvA 提取碼:rrmu
- 在json文件所在目錄,運行json-server
json-server --watch --port 5050 db.json
執行后是如下結果:

如果報錯了,不要急:
·如果是這個問題就請看接下來的方法:
1. 以管理員身份運行PowerShell
2. 執行: get-ExecutionPolicy ,回復Restricted,表示狀態是禁止的
3.接下來執行: set-ExecutionPolicy RemoteSigned
4.選擇Y,就可以解決了
注意:一定要以管理員的身份運行PowerShell,不是cmd窗口!
最終的執行結果是:

接下來需要訪問瀏覽器查看完整db.json http://localhost:5050/db
- get請求(用於查詢數據)
不帶參數:http://localhost:5050/index
帶參數:http://localhost:5050/details/1
- post請求(專門用於插入數據)
$("#postBtn").click(function(){ $.ajax({ type: 'post', url: 'http://localhost:3003/fruits', data: { name: $("#fruitName").val(), price: $("#fruitPrice").val() }, success: function(data){ console.log("post success") }, error:function(){ alert("post error") } }) })
- put請求(專門用於修改數據)
$("#putBtn").click(function(){ $.ajax({ type: 'put', url: 'http://localhost:3003/fruits/'+ $("#putId").val(), data: { price: $("#putPrice").val() }, success: function(data){ console.log("put success") }, error:function(){ alert("put error") } }) })
- delete(專門用於刪除數據)
$("#delOne").click(function(){ $.ajax({ type: 'delete', url: 'http://localhost:3003/fruits/'+ $("#delId").val(), success: function(data){ console.log("del success") }, error:function(){ alert("del error") } }) })
