json-server的安裝使用及出現的問題解決方法


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 

  1. get請求(用於查詢數據)

不帶參數:http://localhost:5050/index

帶參數:http://localhost:5050/details/1

  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")
        }
    })
})
  1. 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")
        }
    })
})
  1. 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")
        }
    })
})

 


免責聲明!

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



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