笔记
API 相关:
API 的分类:
REST API (restful 风格的 API)
1. 发送的请求进行CRUD哪个操作由请求方式来决定
2. 同一个请求路径可以进行多个操作
3. 请求方式会用到 GET/POST/PUT/DELETE
非 REST API(restless 风格的 API
1. 请求方式不决定请求的 CRUD 操作
2. 一个请求路径只对应一个操作
3. 请求方式一般只会用到 GET/POST
使用 json-server 搭建REST API
- json-server 是什么?
用来快速搭建 REST API 的工具包 快速开启一台服务器!
- 使用 json-server
(1)在线文档:https://github.com/typicode/json-server
(2)下载:npm install -g json-server
(3)目标根目录下创建数据库json文件:db.json (任意名).json
使用 postman 测试接口
测试 json-server GET/POST/PUT/DELETE接口
一般 http 请求和 ajax 请求
- ajax请求是一种特别的 http 请求
- 对服务器来说,没有任何区别,区别在浏览器端
- 浏览器发请求:只有 xhr 或者 fetch 发出的才是 ajax 请求,其他所有的都是非 ajax 请求
- 浏览器接受到响应:
(1)一般请求:浏览器一般会直接显示响应体数据,也就是我们常说的自动刷新、跳转页面
(2)ajax 请求:浏览器不会对界面进行任何更新操作(即无刷新),只是调用监控的回调函数并传入响应相关数据
axios 的理解和应用
axios 是什么?
- 前端最流行的 ajax 的请求库
- React/Vue 官方都推荐使用 axios 发 ajax 请求
- 文档:http://github.com/axios/axios
####axios 特点:
- 基本 promise 的异步 ajax 请求库
- 浏览器 / node 端都可以使用
- 支持请求 / 响应拦截器
- 支持请求取消
- 请求 / 响应数据转换
- 批量发送多个请求
使用 axios 发 ajax请求
- axios 调用的返回值是 promise 实例
- 成功的值叫 response ,失败的值叫 error
- axios 成功的值是一个 axios 封装的 response 对象,服务器返回的真正数据在 response.data 中
1. 发送 GET 请求
<body>
<button id="btn">点我获取所有人的信息</button>
<script>
//获取按钮
const btn = document.getElementById('btn');
//获取所有人的信息 发送GET请求 --- 不携带参数
btn.onclick = () => {
//此处写axios代码!
}
</script>
axios 完整版:
const result = axios({
url: 'http://localhost:5000/persons',//请求地址
method: 'GET',//请求方式
});
result.then(
response => {console.log('请求成功了!', response.data);},
error => {console.log('请求失败了,', error);}
);
axios 精简版:
axios.get('http://localhost:5000/persons').then(
response => { console.log('请求成功了!', response.data); },
error => { console.log('请求失败了,', error); }
);
axios get请求发送时携带query参数:
<body>
<button id="btn1">点我获取所有人的信息</button><br><br>
<button id="btn2">点我获取某个人的信息</button>
<input type="text" id="person_id" placeholder="请输入id">
<!--
1. axios 调用的返回值是 promise 实例
2.成功的值叫 response,失败的值叫 error
3.axios成功的值是一个axios封装的response对象,服务器返回的真正数据在response.data中
4.携带query参数时,编写的配置项叫做params
-->
<script>
//获取按钮
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
const personId = document.getElementById('person_id');
//获取所有人的信息 发送GET请求 --- 不携带参数
btn1.onclick = () => {
...........
}
//获取某个人的信息 发送get请求 --- 携带query参数
btn2.onclick = () => {
//此处写入axios代码
}
</script>
</body>
axios 完整版:
axios({
url:'http://localhost:5000/person',
method:'GET',
params:{id:personId.value}//此处写的params但其实传的是query参数
}).then(
response =>{console.log('成功了',response.data);},
error =>{console.log('失败了',error);}
)
axios 精简版:
axios.get('http://localhost:5000/person',{params:{id:personId.value}},).then(
response =>{console.log('成功了',response.data);},
error =>{console.log('失败了',error);}
)
发送 POST 请求:
示例代码:
<body>
<button id="btn1">点我获取所有人的信息</button><br><br>
<button id="btn2">点我获取某个人的信息</button>
<input type="text" id="person_id" placeholder="请输入id">
<button id="btn3">点我添加一个人</button>
<input type="text" id="person_age" placeholder="请输入age">
<input type="text" id="person_name" placeholder="请输入name"><br><br>
<!--
1. axios 调用的返回值是 promise 实例
2.成功的值叫 response,失败的值叫 error
3.axios成功的值是一个axios封装的response对象,服务器返回的真正数据在response.data中
4.携带query参数时,编写的配置项叫做params
-->
<script>
//获取按钮
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
const btn4 = document.getElementById('btn4');
const personId = document.getElementById('person_id');
const personAge = document.getElementById('person_age');
const personName = document.getElementById('person_name');
//获取所有人的信息 发送GET请求 --- 不携带参数
btn1.onclick = () => {
...........
}
//获取某个人的信息 发送get请求 --- 携带query参数
btn2.onclick = () => {
...........
}
//添加某个人 发送post请求 --- 携带请求体body参数
btn3.onclick = () =>{
//此处写入axios代码
}
</script>
</body>
axios 完整版:
axios({
url:'http://localhost:5000/person',
method:'POST',
// data:{name:personName.value,age:personAge.value},//携带请求体参数(默认json编码)
data:`name=${personName.value}&age=${personAge.value}`,//携带请求体参数(urlencoded编码)
}).then(
response =>{console.log('成功了'+response.data);},
error =>{console.log('失败了'+error);}
)
axios 精简版:
//使用对象就会默认是json编码模式
//axios.post('http://localhost:5000/person',{name:personName.value,age:personAge.value}).then(
//是用字符串就会默认是urlencoded编码模式
axios.post('http://localhost:5000/person',`name=${personName.value}&age=${personAge.value}`).then(
response =>{console.log('成功了'+response.data);},
error =>{console.log('失败了'+error);}
)
备注:axios 底层源码中也是写入一个判断,假如第二个空中为对象则使用 JSON.stringify 来解码,假如第二个空为模板字符串则使用urlencoded方式来解码。
发送 PUT 请求:
示例代码:
<body>
<button id="btn1">点我获取所有人的信息</button><br><br>
<button id="btn2">点我获取某个人的信息</button>
<input type="text" id="person_id" placeholder="请输入id"><br><br>
<button id="btn3">点我添加一个人</button>
<input type="text" id="person_age" placeholder="请输入age">
<input type="text" id="person_name" placeholder="请输入name"><br><br>
<button id="btn4">点我更新一个人</button>
<input type="text" id="person_update_id" placeholder="请输入一个人的id">
<input type="text" id="person_update_age" placeholder="请输入一个人的年龄">
<input type="text" id="person_update_name" placeholder="请输入一个人的姓名">
<!--
1. axios 调用的返回值是 promise 实例
2.成功的值叫 response,失败的值叫 error
3.axios成功的值是一个axios封装的response对象,服务器返回的真正数据在response.data中
4.携带query参数时,编写的配置项叫做params
-->
<script>
//获取按钮
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
const btn3 = document.getElementById('btn3');
const btn4 = document.getElementById('btn4');
const personId = document.getElementById('person_id');
const personAge = document.getElementById('person_age');
const personName = document.getElementById('person_name');
const personUpdateId = document.getElementById('person_update_id');
const personUpdateAge = document.getElementById('person_update_age');
const personUpdateName = document.getElementById('person_update_name');
//获取所有人的信息 发送GET请求 --- 不携带参数
btn1.onclick = () => {
........
}
//获取某个人的信息 发送get请求 --- 携带query参数
btn2.onclick = () => {
........
}
//添加某个人 发送post请求 --- 携带请求体body参数
btn3.onclick = () => {
........
}
//更新一个人 发送PUT请求--携带json编码参数 或 urlencoded编码
btn4.onclick = () => {
//此处写入axios代码
}
</script>
</body>
axios 完整版:
//完整版
axios({
url: 'http://localhost:5000/person',
method: 'PUT',
data:{
id:personUpdateId.value,
name:personUpdateName.value,
age:personAge.value
}
}).then(
response => { console.log('成功了' + response.data); },
error => { console.log('失败了' + error); }
)
axios 精简版:
//精简版
axios.put("http://localhost:5000/person",{
id:personUpdateId.value,
name:personUpdateName.value,
age:personAge.value,
}).then(
response => { console.log('成功了' + response.data); },
error => { console.log('失败了' + error); }
)
发送 DELETE 请求:
<body>
<button id="btn1">点我获取所有人的信息</button><br><br>
<button id="btn2">点我获取某个人的信息</button>
<input type="text" id="person_id" placeholder="请输入id"><br><br>
<button id="btn3">点我添加一个人</button>
<input type="text" id="person_age" placeholder="请输入age">
<input type="text" id="person_name" placeholder="请输入name"><br><br>
<button id="btn4">点我更新一个人</button>
<input type="text" id="person_update_id" placeholder="请输入一个人的id">
<input type="text" id="person_update_age" placeholder="请输入一个人的年龄">
<input type="text" id="person_update_name" placeholder="请输入一个人的姓名"><br><br>
<button id="btn5">点我删除一个人</button>
<input type="text" id="person_delete_id" placeholder="请输入一个人的id">
<!--
1. axios 调用的返回值是 promise 实例
2.成功的值叫 response,失败的值叫 error
3.axios成功的值是一个axios封装的response对象,服务器返回的真正数据在response.data中
4.携带query参数时,编写的配置项叫做params
5.携带params参数时,就需要自己手动拼在URL中
-->
<script>
//获取按钮
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
const btn3 = document.getElementById('btn3');
const btn4 = document.getElementById('btn4');
const btn5 = document.getElementById('btn5');
const personId = document.getElementById('person_id');
const personAge = document.getElementById('person_age');
const personName = document.getElementById('person_name');
const personUpdateId = document.getElementById('person_update_id');
const personUpdateAge = document.getElementById('person_update_age');
const personUpdateName = document.getElementById('person_update_name');
const personDeleteId = document.getElementById('person_delete_id');
//获取所有人的信息 发送GET请求 --- 不携带参数
btn1.onclick = () => {
.........
}
//获取某个人的信息 发送get请求 --- 携带query参数
btn2.onclick = () => {
.........
}
//添加某个人 发送post请求 --- 携带请求体body参数
btn3.onclick = () => {
........
}
//更新一个人 发送PUT请求--携带json编码参数 或 urlencoded编码
btn4.onclick = () => {
.........
}
//删除一个人 发送delete请求---携带params参数
btn5.onclick = () => {
//此处写入axios代码
}
</script>
</body>
axios 代码:
//使用的params参数的方式
axios({
url:`http://localhost:5000/person/${personDeleteId.value}`,
method:'DELETE',
}).then(
response =>{console.log('成功了',response.data);},
error =>{console.log('失败了',error);}
)
axios 常用配置:
axios 共有37个配置
这里介绍几个常用的:
axios({
url:"http://localhost:5000/test1",//请求地址
method:'GET',//请求方式
params:{delay:3000,b:2},//配置query参数
data:{c:3,d:4},//配置请求体参数(json编码)
data:`e=5&f=6`,//配置请求体参数(urlencoded编码)
timeout:2000,//配置超市时间
Headers:{demo:123},//配置请求头
responseType: 'json'//配置响应数据的格式(默认是json)
})
axios 可以全局配置:
//给axios配置默认属性
axios.defaults.timeout= 2000;//配置了默认超时时间
axios.defaults.headers={school:'金科'};//配置每个请求的请求头都自带的内容
axios.defaults.baseURL='http://localhost:5000';
//配置请求的地址,若不配置,则axios默认从自身的地址发送请求;若配置了,写请求时不需要带以上写过的地址,只需要写后面的地址会自动拼接!
axios.create(config):
- 根据指定配置创建一个新的 axios ,也就是每个新 axios 都自己的配置
- 新的 axios 只是没有取消请求和批量发请求的方法,其他所有的语法都是一致的,所以不是100%一样
- 为什么要这个语法?
需要:项目中有部分接口需要的配置与另一部分接口需要的配置不一样
示例代码:
<body>
<button id="btn1">点我获取所有人</button>
<button id="btn3">点我获取笑话信息</button>
<script>
const btn1 = document.getElementById('btn1');
const btn3 = document.getElementById('btn3');
//配置axios.create的内容
const axios2 = axios.create({
baseURL:'https//api.apiopen.top',
timeout:3000,
// headers:{name:'王成'}
})
//给axios配置默认属性
axios.defaults.timeout = 2000;
axios.defaults.headers = { school: '金科' };
axios.defaults.baseURL = 'http://localhost:5000';
btn1.onclick = () => {
axios({
..........
}
btn3.onclick = () => {
axios2({
url:'/getJoke',
method:'GET',
}).then(
response =>{console.log('成功了',response.data);},
error =>{console.log('失败了',error);}
)
}
</script>
</body>
备注:axios.create( ) 配置 需要写在 axios 全局配置的前面,否则会报错(目前版本0.27.2)之前某个版本可用
个人遇到的问题是:https//api.apiopen.top/getJoke 这个官网可能已经停止了 所以不一定收到能收到笑话!
axios拦截器:
请求拦截器:
- 是什么?
在真正发送请求前执行的一个回调函数
- 作用:
对所有的请求做统一处理:追加请求头、追加参数、界面loading提示等等
//请求拦截器 需求:在请求发出时判断时间戳是否是2的倍数,如果是,则加个请求头
axios.interceptors.request.use(config => {
if(Date.now()%2 === 0){
config.headers.school = 'jit';
}
return config;
});
注意:一定要写 return 否则请求将会在拦截器处被停止!
响应拦截器:
- 是什么?
得到响应之后执行的一组回调函数
- 作用:
若请求成功,对成功的数据进行处理
若请求失败,对失败进行进一步操作
//响应拦截器
axios.interceptors.response.use(response => {
console.log("响应拦截器成功的回调执行了", response);
if (Date.now() % 2 === 0) { return response.data; }
return '时间戳不是偶数,不能给你';
}, error => {
console.log('响应拦截器失败的回调执行了', error);
alert(error);
return new Promise(()=>{});//此时的promise链停下来了
});
btn1.onclick = async () => {
/* axios.get('http://localhost:5000/persons').then(
response => { console.log('成功了', response); },
error => { console.log('失败了', error); }
)*/
const result = await axios.get('http://localhost:5000/persons');
console.log(result);//此处为返回的请求成功的data
}
解释:写了响应拦截器后,不需要写请求返回后失败的回调,因为错误在拦截器中就已经显示了错误信息了,错误后将返回 promise 的 pending 状态,用此来中断 promise链的传递,即不用到 axios( ).then 中的失败回调,响应拦截器已经处理了,所以 axios( ).then 只会收成功的回调,catch 也不需要写。
示例代码:
<body>
<button id="btn1">点我获取所有人</button>
<script>
const btn1 = document.getElementById('btn1');
//请求拦截器
axios.interceptors.request.use(config => {
if (Date.now() % 2 === 0) {
config.headers.school = 'jit';
}
console.log('请求拦截器执行了');
return config;
});
//响应拦截器
axios.interceptors.response.use(response => {
console.log("响应拦截器成功的回调执行了", response);
if (Date.now() % 2 === 0) {
return response.data;
}
return '时间戳不是偶数,不能给你';
}, error => {
console.log('响应拦截器失败的回调执行了', error);
alert(error);
return new Promise(()=>{});//此时的promise链停下来了
});
btn1.onclick = async () => {
/* axios.get('http://localhost:5000/persons').then(
response => { console.log('成功了', response); },
error => { console.log('失败了', error); }
)*/
const result = await axios.get('http://localhost:5000/persons');
console.log(result);
}
</script>
</body>
一个很小的点:如果有多个请求拦截器,则先写的后调用,后写的先调用。
axios 取消请求:
注意:此方法(CancelToken),官方已经不推荐,推荐去看官网的方法
示例代码:
<body>
<button id="btn1">点我获取测试数据</button>
<button id="btn2">取消请求</button>
<script>
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
const {CancelToken} = axios; //CancelToken能为一次请求‘打标识’
let cancel;
btn1.onclick = async () => {
axios({
url:'http://localhost:5000/test1?delay=3000',
cancelToken: new CancelToken((c)=>{ //c是一个函数,调用c就可以关闭本次请求
cancel = c;
})
}).then(
response =>{console.log('成功了',response);},
error =>{console.log('失败了',error);}
)
}
btn2.onclick = () =>{
cancel();
}
</script>
</body>
步骤操作:
- 首先定义一个 CancelToken 来接收 axios 中 CancelToken 主要是为了’打标识‘
const {CancelToken} = axios; //CancelToken能为一次请求‘打标识’
- 然后定义一个 cancel 变量
let cancel;
- 在 axios 对象中配置 cancelToken:
cancelToken: new CancelToken((c)=>{ //c是一个函数,调用c就可以关闭本次请求 cancel 的缩写
cancel = c;//赋值给外面的变量cancel 提升c的作用域?
})
- 最后绑定在某个事件发生后想取消请求时调用:
//笔记中所写的事件为点击事件 任何事件都可以
btn2.onclick = () =>{
cancel();
}
优化取消请求(细化错误问题):
说明:点击取消请求时,axios也会去失败的回调,但这不是服务器的错误导致的,是用户自身不需要本次请求,所以需要对于错误进行划分。以及如果用户反复点击,会发出多次请求,单只需要一次请求。
示例代码:
<body>
<button id="btn1">点我获取测试数据</button>
<button id="btn2">取消请求</button>
<script>
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
const { CancelToken, isCancel } = axios //CancelToken能为一次请求‘打标识’
let cancel;
btn1.onclick = async () => {
if(cancel) cancel();//避免多次反复请求
axios({
url: 'http://localhost:5000/test1?delay=3000',
cancelToken: new CancelToken((c) => { //c是一个函数,调用c就可以关闭本次请求
cancel = c;
})
}).then(
response => { console.log('成功了', response); },
error => {
if (isCancel(error)) {
//如果进入判断,证明:是用户取消了请求
console.log('用户取消了请求,原因是', error.message);
} else {
console.log('失败了', error);
}
}
)
}
btn2.onclick = () => {
cancel("任性,我就是不想要了");
}
</script>
</body>
解释:cancel 函数可在括号中添加说明,在进入失败的回调时进行判断是服务器端发出的,还是用户自己取消的。
axios 请求拦截器中使用取消请求:
示例代码:
<body>
<button id="btn1">点我获取测试数据</button>
<button id="btn2">取消请求</button>
<script>
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
const { CancelToken, isCancel } = axios //CancelToken能为一次请求‘打标识’
let cancel;
//请求拦截器
axios.interceptors.request.use(config => {
if(cancel) cancel('取消了');
config.cancelToken =new CancelToken((c)=> cancel = c);
return config;
});
//响应拦截器
axios.interceptors.response.use(response => {
return response.data;
},error => {
if (isCancel(error)) {
//如果进入判断,证明:是用户取消了请求
console.log('用户取消了请求,原因是', error.message);
} else {
console.log('失败了', error);
}
return new Promise(()=>{});
});
//进行简化
btn1.onclick = async () => {
const result = await axios.get('http://localhost:5000/test1?delay=3000');
console.log(result);
}
btn2.onclick = () => {
cancel("我不想要了");
}
</script>
</body>
拦截器代码:
//请求拦截器
axios.interceptors.request.use(config => {
if(cancel) cancel('取消了');
config.cancelToken =new CancelToken((c)=> cancel = c);
return config;
});
//响应拦截器
axios.interceptors.response.use(response => {
return response.data;
},error => {
if (isCancel(error)) {
//如果进入判断,证明:是用户取消了请求
console.log('用户取消了请求,原因是', error.message);
} else {
console.log('失败了', error);
}
return new Promise(()=>{});
});
解释:取消请求的配置写在请求拦截器中,首先加入判断来防止多次重复请求,然后在响应拦截器中写入失败的回调且进行判断,是服务器的错误,还是客户端取消请求,最后中断 Promise 链,由此 axios 中只需要写入成功的回调即可。
axios 批量发送请求:
使用了axios.all( ) 的API,括号中为数组,其中写需要并发的请求。
示例代码:
<body>
<button id="btn1">点我获取测试数据</button>
<script>
const btn1 = document.getElementById('btn1');
btn1.onclick = async () => {
axios.all([
axios.get('http://localhost:5000/test1'),
axios.get('http://localhost:5000/test2'),
axios.get('http://localhost:5000/test3'),
]).then(
response =>{console.log(response);},
error =>{console.log(error);}
)
};
</script>
</body>
解释:Axios.all( ) 基于 promise.all( ),所有的都是成功的回调才会返回数据,如果有一个失败的回调,就会走错误信息。此方法会按顺序打印 并发的三个请求的数据,并且如果用了延迟请求也会是原本的顺序,这是 axios 封装好的。