axios 数据请求

axios 数据请求

四月 10, 2020

axios

Get 请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// get请求
// 用法1
// axios.get(url,{params}) url是后端接口, params是携带参数的选项
// axios.get('http://59.110.226.77:3000/api/list/hot', {
// params: {
// cid: 17
// }
// })
// .then(res => {
// console.log('res', res)
// })
// .catch(error => Promise.reject(error))

// 用法2
// axios(requestConfig)
axios({
url: "http://59.110.226.77:3000/api/list/hot",
// method: 'get', 默认get
params: {
cid: 16,
},
})
.then((res) => {
console.log("res", res);
})
.catch((error) => Promise.reject(error));

Post-json 请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// post-json请求
axios({
url: "http://59.110.226.77:3000/api/user/login",
method: "post",
data: {
// post请求在data中发送
username: this.username,
password: this.pass,
},
})
.then((res) => {
console.log("res", res);
})
.catch((error) => Promise.reject(error));

Post-form 请求

1
2
3
4
5
6
7
8
9
10
11
12
13
// post-form请求
const p = new URLSearchParams(); // 新建URL实例
p.append("username", this.username); // 增加
p.append("password", this.pass); // 增加
axios({
url: "http://59.110.226.77:3000/api/user/login",
method: "post",
data: p, // 实例写在data中
})
.then((res) => {
console.log("res", res);
})
.catch((error) => Promise.reject(error));

Post-file 请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function upload(e) {
const p = new FormData(); // 图片必须以二进制才能传递给后端
p.append("file", e.target.files[0]); // 通过事件对象e来得到图片的实例
axios({
url: "https://elm.cangdu.org/v1/addimg/shop",
method: "post",
data: p,
})
.then((res) => {
console.log("res", res);
this.pic = "https://elm.cangdu.org/img/" + res.data.image_path;
})
.catch((error) => Promise.reject(error));
}

axios 自定义请求实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 创建自定义请求实例
const ins = axios.create({
// 超时自动取消请求
timeout: 20000,
// 统一设置数据请求基准地址
baseURL: "http://59.110.226.77:3000/api",
});

ins
.get("/list/sell", {
params: {
cid: 17,
},
})
.then((res) => {
console.log("res", res);
})
.catch((error) => Promise.reject(error));

axios 拦截器

axios 的拦截器是用于拦截请求和响应的,也就是在数据请求前做点事,在数据请求到之后做点事

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// 创建自定义请求实例
const ins = axios.create({
// 超时自动取消请求
timeout: 20000,
// 统一设置数据请求基准地址
baseURL: "http://59.110.226.77:3000/api",
});

// 请求拦截器
ins.interceptors.request.use(
(config) => {
// 发生请求前的处理
// token
// config.headers.common['自定义'] = cookie.get('token')
return config;
},
(error) => {
// 请求错误处理

return Promise.reject(error);
}
);

// 响应拦截器
ins.interceptors.response.use(
(res) => {
// 假设后端给你的不是你想要的,你怎么办

// 数据格式化

return res;
},
(error) => {
// 响应错误处理

return Promise.reject(error);
}
);

并发请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
axios
.all([
axios.get("http://59.110.226.77:3000/api/list/hot", {
params: {
cid: 17,
},
}),
axios.get("http://59.110.226.77:3000/api/list/price", {
params: {
cid: 17,
},
}),
])
.then(
axios.spread((res1, res2) => {
console.log("res1", res1);
console.log("res2", res2);
})
);