axios笔记
一、axios是什么
前端最流行的ajax请求库
二、json-server
json-server可以帮助我们搭建http服务
为什么要搭建http服务?
:是因为我们用axios的时候,需要向服务端发送请求
我们需要服务端这样一个角色,来与axios结合做实践
1. Install JSON Server
npm install -g json-server
2. Create a db.json filewith some data
{"posts": [ //文章{"id": 1,"title": "json-server","author": "typicode"}],"comments": [ //评论{"id": 1,"body": "some comment","postId": 1}],"profile": { //个人信息"name": "typicode"}
}//这是一个json格式的字符串
加 npx 是全局查找的意思,一般插件用-g安装的前面需要加
3. Start JSON Server
npx json-server --watch db.json
GET | /posts |
GET | /posts/1 |
POST | /posts |
PUT | /posts/1 |
PATCH | /posts/1 |
DELETE | /posts/1 |
三、axios的介绍与页面配置
axios是基于Promise的HTTP客户端,可以在浏览器和 node.js 两个环境去运行
- 在浏览器端借助axios,可以向服务端发送ajax请求来获取数据
- 在 node.js 中向远端服务发送HTTP请求
1. 特点
- 可以在浏览器端发送ajax请求
- 可以在 node.js 环境中发送HTTP请求
- 支持Promise的API
- 请求响应拦截器(这是axios非常重要的一个特性,它可以在请求之前做一些准备工作,在响应回来之后可以对一些结果做预处理)
- 可以帮我们对请求和响应数据做转换
- 取消请求
- 自动将结果转换为json数据
- 可以做保护,阻挡XSRF
2. Installing
方式一:
npm install axios
在项目当中,我们会通过打包工具对其做一个引入
方式二:
bower install axios
这样的安装我们会页面当中通过script标签对其引入来使用
方式三:
yarn add axios
方式四:使用CDN引入
<script src = "https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
我们在开发的过程中一般都是用方式一和方式三
但在学习过程中我们使用方式四
如果在访问该网址时速度比较慢,我们可以换成中国的CDN
在BootCDN中搜索axios复制链接
四、axios的基本使用
传入的参数是一个对象,里面有它的配置项
axios({//请求类型method: ,//URLurl:
}).then(response => {console.log(response)
})
- axios的返回结果是一个Promise对象,所以可以用then方法指定成功的回调
- method大小写都可以
增删改查
1. 获取数据
btns[0].onclick = function () {axios({method: 'GET',url: 'http://localhost:3000/posts/2'}).then(response => {console.log(response);})}
2. 添加一篇新的文章
btns[1].onclick = function () {axios({method: 'POST',url: 'http://localhost:3000/posts',//设置请求体data: {title: '鱼的记忆',author: '七年级小卓'}}).then(response => {console.log(response);})
}
请求体是一个json格式的字符串,此时就把内容传递给服务器,json-server这个服务收到数据过后就把数据做一个保存(此时你返回db.json文件中已经保存了你添加的文章)
3. 更新数据
btns[2].onclick = function () {axios({method: 'PUT',url: 'http://localhost:3000/posts/ab9e',data: {title: '鱼的记忆',author: '七年级小卓'}}).then(response => {concole.log(response);})
}
4. 删除数据
btns[3].onclick = function () {axios({method: 'DELETE',url: 'http://localhost:3000/posts/2'}).then(response => {console.log(response);})
}
axios其他方式发送请求
除了用axios的函数发送请求之外,还有axios对象身上的一系列http请求类型的方法也可以用来发送请求
1. axios.request
btns[0].onclick = function () {axios.request({method: 'GET',url: 'http://localhost:3000/comments'}).then(response => {console.log(response);})
}
2. axios.post
btns[1].onclick = function () {axios.post('http://localhost:3000/comments',{"body": "文豪野犬","postId": 2}).then(response => {console.log(response);})
}
就不一一演示了
五、axios请求响应结果的结构
- config:配置对象
- data:响应体,也就是服务器返回结果(axios自动的将服务器返回结果进行了json解析,把它转成了一个对象)
- headers:响应头信息
- request:原生的ajax请求对象。axios用来发送ajax请求,而发送ajax请求就要用到底层的XMLHttpRequest实例对象,request这个属性保存的就是当前axios在发送请求时创建的那个ajax请求对象
- status:响应状态码
- statusText:响应的状态字符串
六、Config配置对象详细说明
axios的请求对象,这个对象指的就是axios在调用时它所接收的参数对象
{//指明这个请求要发给谁url: '/user',//设置请求的类型method: 'get',//设置URL的基础结构baseURL: 'https://some-domain.com/api/',//对请求的数据做一个处理,处理完之后向服务器进行发送transformRequest: [function (data, headers) {return data;}],//对响应的结果做一些改变,改变完之后我们再用自定义的回调去处理这个结果transformResponse: [function (data) {return data;}]//对请求头信息进行配置//在某些项目当中,进行身份校验的时候它要求你在头信息中加入一个身份的标识然后检验我的请求是否满足条件,这个时候就可以借助headers对请求头信息做一个控制headers: {'X-Requested-With': 'XMLHttpRequest'},//来设定URL参数的params: {ID: 12345}// paramsSerializer: {},//请求头设置data: {firstName: 'Fred'},//data: 'Country=Brasil&City=Belo Horizonte',//超时时间,超过这个时间请求就会取消timeout: 1000, // default is `0` (no timeout)//在跨域请求时对cookie的携带进行设置 withCredentials: false, // default//对请求的适配器进行设置:1.发送ajax的 2. 在node.js里面发送http请求的adapter: function (config) {/* ... */},adapter: 'xhr' 请求基础验证,设置用户名和密码的auth: {username: 'janedoe',password: 's00pers3cret'},//对响应体的格式进行设置,默认值是jsonresponseType: 'json',//字符集设置,响应结果的编码responseEncoding: 'utf8',//对cookie的名字进行设置xsrfCookieName: 'XSRF-TOKEN',//对头信息做一个设置xsrfHeaderName: 'X-XSRF-TOKEN',//以上进行了安全设置(保证了我们的信息是来自于客户端,而不是其他的页面)//在上传的时候的回调onUploadProgress: function (progressEvent) {},//在下载的时候的回调onDownloadProgress: function (progressEvent) {},//设置http响应体的最大尺寸,单位为字节maxContentLength: 2000,//请求体的最大内容maxBodyLength: 2000,//对响应结果的成功进行设置,什么情况下会认定它是成功的validateStatus: function (status) {return status >= 200 && status < 300; // default},//最大跳转的次数maxRedirects: 21, // default//beforeRedirect: (options, { headers }) => {if (options.hostname === "example.com") {options.auth = "user:password";}},//设置socket文件的位置,作用:向docker的进程发送请求socketPath: null, // default//transport: undefined, // default//对客户端的信息做一些设置httpAgent: new http.Agent({ keepAlive: true }),httpsAgent: new https.Agent({ keepAlive: true }),//设置代理proxy: {protocol: 'https',host: '127.0.0.1',// hostname: '127.0.0.1' // Takes precedence over 'host' if both are definedport: 9000,auth: {username: 'mikeymike',password: 'rapunz3l'}},//对ajax请求做一个取消的设置cancelToken: new CancelToken(function (cancel) {}),//signal: new AbortController().signal,//是否要对响应结果做一个解压,只能在node环境中设置decompress: true, //insecureHTTPParser: undefined,//transitional: {//silentJSONParsing: true, //forcedJSONParsing: true,//clarifyTimeoutError: false,},env: {// FormData: window?.FormData || global?.FormData},formSerializer: {visitor: (value, key, path, helpers) => {};dots: boolean; metaTokens: boolean; indexes: boolean; },// maxRate: [100 * 1024, 100 * 1024 ]
}
data有对象和字符串两种设置形式
- 如果是对象形式,会转成json字符串传递
- 如果是字符串形式,会直接传递
七、axios的默认配置
可以把重复性的设置写在默认配置里面以简化代码
axios.defaults.method = 'get';
axios.defaults.baseURL = 'http://localhost:3000';btns[0].onclick = function () {axios({url: '/posts'}).then(response => {console.log(response);})
}
八、axios创建实例对象发送请求
const duanzi = axios.create({baseURL: 'https://api.apiopen.top/api',timeout: 2000
});
duanzi({url: '/getmages',
}).then(response => {console.log(response);
});
这里duanzi 和 axios对象的功能几乎是一样的
借用于封装好的方法去发送请求也是可以的
优势:
假如我们的项目它的接口数据服务不是来自于单一的服务器,比如说有a和b两个服务器。给a发送请求时就要设置a的域名和端口,这时候如果用默认配置去做的话,只能让一个服务器好使。
我们可以创建两个实例对象发送请求就可以解决这个问题
九、axios拦截器
拦截器是一些函数:
- 请求拦截器
- 响应拦截器
1. 请求拦截器:
(1)作用:在发送请求之前,我们可以借助一些回调函数来对请求参数和内容做一些处理和检测。没问题则发送请求,有问题则取消
(2)在请求拦截器中我们可以对config配置对象进行处理
2. 响应拦截器:
当服务器返回结果之后,响应拦截器可以在回调函数处理结果之前先对结果进行预处理。没问题再交由我们自定义的回调函数进行处理,如果有问题就直接在响应拦截器中处理掉了
axios.interceptors.request.use(function(config) {console.log('请求拦截器 成功')return config;
}, function(error) {console.log('请求拦截器 失败')return Promise.reject(error);
});axios.interceptors.response.use(function(response) {console.log('响应拦截器 成功')return response;
}, function(error) {console.log('响应拦截器 失败')return Promise.reject(error);
});axios({method: 'GET',url: 'http://localhost:3000/posts'
}).then(response => {console.log('自定义的回调函数返回结果')
})
- 请求拦截器是后进先执行
- 响应拦截器是先进先执行
十、axios取消请求
axios取消请求的步骤:
一、cancelToken
//2. 定义全局变量
let cancel = null;
axios({method: 'GET',url: 'http://localhost:3000/posts',//1. 添加配置对象的属性cancelToken: new axios.cancelToken(function(c) {//3. 将c的值赋值给cancelcancel = c;})
})
二、