【笔记】Axios学习笔记

前言

易用、简洁且高效的http库(官网

下载依赖

1
npm install axios

引入依赖

1
import axios from "axios";

发送请求

  • 返回Promise对象

根据指定配置发送请求

url:如果定义的是包含根路径的URL路径,则直接使用这个URL;如果定义的是不含根路径的URL路径,则会将baseURL作为根路径
method:请求方法

GETPOSTPUTDELETEPATCHHEAD

baseURL:定义请求的根路径
headers:定义请求头
params:定义query查询字符串
data:定义请求体
timeout:定义请求超时时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const config = {
url: "/api",
method: "GET",
baseURL: "http://127.0.0.1:8080",
headers: {
"key": "value"
},
params: {
key: "value"
},
data: {
key: "value"
},
timeout: 1000
};

axios.request(config).then(function (res) {
return res.data
}).then(function (res) {
...
}).catch(function (err) {
...
});

发送GET请求

1
axios.get("http://127.0.0.1:8080/?key=value");
1
2
3
4
5
axios.get("http://127.0.0.1:8080", {
params: {
key: "value"
}
})

发送POST请求

1
2
3
4
5
axios.post("http://127.0.0.1:8080", {
data: {
key: value
}
});

config:配置对象

1
2
3
axios.post("http://127.0.0.1:8080", {
key: value
}, config);

发送DELETE请求

1
axios.delete("http://127.0.0.1:8080");

config:配置对象

1
axios.delete("http://127.0.0.1:8080", config);

发送HEAD请求

1
axios.head("http://127.0.0.1:8080");

config:配置对象

1
axios.head("http://127.0.0.1:8080", config);

发送PUT请求

config:配置对象
data:请求体参数对象

1
axios.put("http://127.0.0.1:8080", config);
1
axios.put("http://127.0.0.1:8080", data, config);

发送PATCH请求

config:配置对象
data:请求体参数对象

1
axios.patch("http://127.0.0.1:8080", config);
1
axios.patch("http://127.0.0.1:8080", data, config);

并发多请求

1
2
3
4
5
6
7
axios.all([
axios.get("http://127.0.0.1:8080"),
axios.get("http://127.0.0.1:8080")
]).then(function (res) {
console.log(res[0].data);
console.log(res[1].data);
});

Axios的实例

默认实例

1
2
3
import axios from "axios"

console.log(axios);

创建新的实例

1
2
3
4
import axios from "axios"

const axiosNew = axios.create();
console.log(axiosNew);

全局配置

配置根路径

1
axios.defaults.baseURL = "http://127.0.0.1:8080";

配置拦截器

配置请求拦截器

1
2
3
4
5
6
7
8
axios.interceptors.request.use(function (config) {

...

return config;
}, function (err) {
return err;
});

配置响应拦截器

1
2
3
4
5
6
7
8
axios.interceptors.response.use(function (res) {

...

return res.data;
}, function (err) {
return err;
});

完成

参考文献

官网中文文档
哔哩哔哩——黑马程序员