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