1. 自己创建一个API
1.1 API 的分类
- REST API: restful (Representational State Transfer (资源)表现层状态转化)
(1) 发送请求进行CRUD 哪个操作由请求方式来决定
(2) 同一个请求路径可以进行多个操作
(3) 请求方式会用到GET/POST/PUT/DELETE - 非REST API: restless
(1) 请求方式不决定请求的CRUD 操作
(2) 一个请求路径只对应一个操作
(3) 一般只有GET/POST
1.2 使用json-server 搭建REST API
1.2.1 json-server 是什么?
用来快速搭建REST API 的工具包
1.2.2 使用json-server
- 在线文档: https://github.com/typicode/json-server
- 下载:
npm install -g json-server
- 目标根目录下创建数据库 json 文件:
db.json
{
"posts": [
{
"id": 1, "title": "json-server", "author": "typicode" },
{
"id": 2, "title": "json-server2", "author": "typicode" }
],
"comments": [
{
"id": 1, "body": "some comment", "postId": 1 }
],
"profile": {
"name": "typicode" }
}
- 启动服务器执行命令:
json-server --watch db.json
1.2.3 使用浏览器访问测试
http://localhost:3000/posts
http://localhost:3000/posts/1
1.2.4 使用axios 访问测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<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.bootcdn.net/ajax/libs/axios/0.21.1/axios.js"></script>
<script>
function testGet() {
axios.get('http://localhost:3000/posts') // 返回一个数组,数组里有两个对象
// axios.get('http://localhost:3000/posts/1') // 返回一个对象
// axios.get('http://localhost:3000/posts?id=1') // 返回一个数组,数组里有一个对象
.then(response => {
console.log('/posts get', response.data)
})
}
function testPost() {
// 添加数据
axios.post('http://localhost:3000/posts', {
"title": "json-server3", "author": "typicode" })
.then(response => {
console.log('/posts put', response.data)
})
}
function testPut() {
// 更新数据
axios.put('http://localhost:3000/posts/3', {
"title": "json-server_put", "author": "typicode" })
.then(response => {
console.log('/posts post', response.data)
})
}
function testDelete() {
// 删除数据
axios.delete('http://localhost:3000/posts/3')
.then(response => {
console.log('/posts delete', response.data)
})
}
</script>
</body>
</html>
2. XHR 的 ajax 封装 (简单版axios)
2.1 特点
- 函数的返回值为
promise
, 成功的结果为response
, 失败的结果为error
- 能处理多种类型的请求: GET/POST/PUT/DELETE
- 函