一、 Restful API 基于json server mock数据介绍

1. Restul API概述      

 Restful API是一种网络应用程序的设计风格和开发方式,基于HTTP,可以使用XML格式定义或JSON格式定义,它使用URL定位资源,用HTTP动词(GET,POST,DELETE,DETC)描述操作。

2. Restful 特点

Restful

API特点

(1).用URL描述资源。

(2).使用HTTP方法描述行为,使用HTTP状态码表示不同的结果。

(3).使用json交互数据。

   说明1:Restful只是一种风格,并不是强制的标准

   说明2: PUT: 用于替换资源(完整资源),PATCH:用于更新部分资源(部分属性)

3.安装jsonserver  服务器

          cnpm install -g json-server


json server注册测命令是json-server

4.新建db.json 启动服务器

(1).新建db.json

   {

     “users”:[]

  }

(2).  启动json-server

json-server

--watch db.json

然后开启另一个终端: npm start启动应用


5. 使用json-server实现添删改查

(1).添加记录–POST   ---postman中实现


postman模拟添加db.json数据

(1).添加记录–POST--- create-react-app中实现

import axios from 'axios'

const insertJson=()=>{

    axios.post("http://localhost:3000/users",{

        name:"jarry"

      })

}

const

App = () => {

return (

  <>

  <button onClick={insertJson}>插入数据</button>

  </>

 );

}

export default App;


(2)查询记录–GET---postman中实现


postman查询

(2)查询记录–GET-create-react-app中实现

import axios from 'axios'

const getJson=()=>{

    axios.get("http://localhost:3000/users",{

        params:{

          name:"jarry"

        }

      }) .then(res=>{

      console.log("res",res);

    })

}

const App = () => {

return (

  <>

    <button onClick={getJson}>获取数据</button>

  </>

 );

}

export default App;


(3)修改记录–PATCH     postman中实现


postman模拟修改记录

(3)修改记录–PATCH     postman中实现-create-react-app中实现

import axios from 'axios'

const

getJson=()=>{

    axios.patch("http://localhost:3000/users/2",{

          name:"赵刚"

      })

    .then(res=>{

      console.log("res",res);

    })

}

const

App = () => {

return (

  <>

    <button onClick={getJson}>PATCH

修改数据

id:2</button>

  </>

 );

}

export default App;


(4)DELETE记录–DELETE     postman中实现


postman模拟删除记录

(4)DELETE记录–DELETE-create-react-app中实现

import axios from 'axios'

const getJson=()=>{

    axios.delete("http://localhost:3000/users/3")

    .then(res=>{

      console.log("res",res);

    })

}

const App = () => {

return (

  <>

    <button onClick={getJson}>DELETE数据 id:3</button>

  </>

 );

}

export default App;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。