什么是REST API以及REST API的使用

API的分类

  1. REST API(restful)
REST是Representational State Transfer(表现层状态转移)的缩写,它是由罗伊·菲尔丁(Roy Fielding)提出的
  1. 非 REST API(restless)

REST API

  1. 发送请求进行 CRUD 哪个操作由请求方式来决定
  2. 同一个请求路径可以进行多个操作
  3. 请求方式会用到 GET/POST/PUT/DELETE

非 REST API

  1. 请求方式不决定请求的 CRUD 操作
  2. 一个请求路径只对应一个操作
  3. 一般只有 GET/POST

使用json-server搭建REST接口

json-server是什么

    用来快速搭建 REST API 的工具包 source可以是json文件或者js文件

使用

  1. 下载
npm install -g json-server
  1. 目标根目录下创建数据库 json 文件: db.json
{
          
   
	"posts": [{
          
   
		"id": 1,
		"title": "json-server",
		"author": "typicode"
	}],
	"comments": [{
          
   
		"id": 1,
		"body": "some comment",
		"postId": 1
	}],
	"profile": {
          
   
		"name": "typicode"
	}
}
  1. 启动服务器执行命令
json-server --watch db.json
    运行成功的界面如下

测试

使用浏览器测试

  1. http://localhost:3000/posts
    普通get请求

结果

2. http://localhost:3000/posts/1

    params参数

结果

  1. http://localhost:3000/posts?id=1
    query参数

结果

query参数与params参数的异同

    相同点 都能得到相应的数据内容 不同点 得到的数据结构不同 query相当于对于原有的数据结构进行过滤,返回的数据结构中有数组 params直接返回查找到的对象

使用axios测试

    调用then方法得到相应的数据
<body>
    <div>
        <button onclick="testGet()">GET 请求</button>
        <button onclick="testPost()">POST 请求</button>
        <button onclick="testPut()">PUT 请求</button>
        <button onclick="testDelete()">DELETE 请求</button>
    </div>
    <script src="https://cdn.bootcss.com/axios/0.19.0/axios.js"></script>
    <script>
        /* 1. GET 请求: 从服务器端获取数据*/
        function testGet() {
           
    
            // axios.get(http://localhost:3000/posts)
            // axios.get(http://localhost:3000/posts/1) // 获取 id 为 1 的对象
            // axios.get(http://localhost:3000/posts?id=1&id=2) // 获取 id 为1 或 2 的数组
            axios.get(http://localhost:3000/posts?title=json-server&author=typicode)
        }
        /* 2. POST 请求: 向服务器端添加新数据*/
        function testPost() {
           
    
            axios.post(http://localhost:3000/posts, {
           
    
                title: xxx, author: yyyy
            }) // 保存数据
        }
        /* 3. PUT 请求: 更新服务器端已经数据 */
        function testPut() {
           
    
            axios.put(http://localhost:3000/comments/1, {
           
    
                body: yyy, postId: 2
            })
        }
        /* 4. DELETE 请求: 删除服务器端数据 */
        function testDelete() {
           
    
            axios.delete(http://localhost:3000/comments/1)
        }
    </script>
</body>

对于测试POST请求的说明

当我们发送post请求添加数据的时候

    id为我们自动生成,不需要我们指定 如果post请求成功,我们打开db.json就会发现新增加的数据

对于PUT/DELETE请求相同,我们通过db.json都能观察到相应数据的改变

经验分享 程序员 微信小程序 职场和发展