一、json-server的介绍与服务搭建
1. 安装
npm install -g json-server
2. 创建文件
db.json文件内容
{
"posts":[
{
"id":1,
"title":"json-server",
"author":"typicode"
}
],
"comments":[
{
"id":1,
"body":"some comment",
"postId":1
}
],
"profile":{
"name":"typicode"
}
}
3. 启动服务
json-server --watch db.json
点击url可以查看到所有的数据
二、axios
1.介绍
2.下载
3.基本使用
- GET
- POST
- PUT
- DELETE
4.axios其他方式发送请求
5. axios请求响应结果的结构
6. axios默认配置
避免后续反复配置
7. axios创建实例对象发送请求
axios.create()
优势:
- 给多个服务器发送请求的时候方便,因为axios.defaults只能设置一个基础默认url
8.axios拦截器(重要)
-
拦截器:本质是函数
-
拦截器分为两类:
- 请求拦截器:在发送请求之前可以借助一些函数对请求的参数、内容进行一些检测
- 响应拦截器:对响应的结果进行预处理
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
执行顺序:
9.axios取消请求
- 添加配置对象的属性
- 声明全局变量
- 将c的值赋值给cancel
- 取消请求
在发送请求前先取消上一个请求(防止用户抢单等连续点击,导致服务器压力过大)