什么是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都能观察到相应数据的改变

  • 3
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值