最近在公司实习,又到我技术分享了,看了看大家之前分享的,一时想不到分享啥了,发愁ing…
突然想起来最初面实习时,被问过 axios
,就来系统的学习一下啦,看有没有什么可以作为分享的,害。
一、axios
是什么
axios
是一个基于promise
的HTTP
网络请求库,可以作用于浏览器和 node.js
中。它是 isomorphic
的,即同一套代码可以运行在浏览器和node.js
中。
在服务端它使用原生 node.js
的 http
模块发送HTTP请求。
在客户端 (浏览器端)使用 XMLHttpRequests
向服务端发送请求获取数据。
github地址:https://github.com/axios/axio
中文文档:https://www.axios-http.cn/docs/intro
二、特性
- 从浏览器创建
XMLHttpRequests
- 从
node.js
创建http
请求 - 支持
Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换
JSON
数据 - 客户端支持防御
XSRF
三、安装
使用 npm
:
npm install axios
使用 bower
:
bower install axios
使用 yarn
:
yarn add axios
使用 jsDelivr CDN:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
使用 unpkg CDN:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
四、基本使用
在安装了axios
或者引入了CDN后,就可以使用了。
可以向axios()
传递相关配置来创建请求,下面展示一下如何用axios(config)
分别发送 get
、post
、put
、delete
请求。
比如用get
请求获取数据:
axios({
//请求类型
method: 'GET',
//URL,根据自己需求填写 URL
url: 'http://localhost:3000/posts/2',
}).then(response => {
console.log(response);
});
比如用post
请求新增数据:
axios({
//请求类型
method: 'POST',
//URL,根据自己需求填写 URL
url: 'http://localhost:3000/posts',
//设置请求体,根据自己需求填写
data: {
title: "我是一个标题"
}
}).then(response => {
console.log(response);
});
比如用put
请求更新数据:
axios({
//请求类型
method: 'PUT',
//URL,根据自己需求填写 URL
url: 'http://localhost:3000/posts/3',
//设置请求体,根据自己需求填写
data: {
title: "我是更新后的标题"
}
}).then(response => {
console.log(response);
});
比如用delete
请求删除数据:
axios({
//请求类型
method: 'DELETE',
//URL,根据自己需求填写 URL
url: 'http://localhost:3000/posts/3',
}).then(response => {
console.log(response);
});
五、axios
常用语法
-
axios(config)
:通用/最本质的发任意类型请求的方式 -
axios(url[, config])
:可以只指定url
发get
请求 -
axios.request(config)
:等同于axios(config)
-
axios.get(url[, config])
:发get
请求 -
axios.post(url[, data, config])
:发post
请求 -
axios.put(url[, data, config])
:发put
请求 -
axios.delete(url[, config])
:发delete
请求 -
axios.defaults.xxx
:请求的默认全局配置 -
axios.interceptors.request.use()
:添加请求拦截器 -
axios.interceptors.response.use()
:添加响应拦截器 -
axios.create([config])
:创建一个新的axios
(它没有下面的功能) -
axios.Cancel()
: 用于创建取消请求的错误对象 -
axios.CancelToken()
:用于创建取消请求的