axios API

axios API

axios 的底层是用了 XMLHttpRequest(xhr)方式发送请求和接收响应,

xhr 相对于之前讲过的 fetch api 来说,功能更强大,

但由于是比较老的 api,不支持 Promise,axios 对 xhr 进行了封装,使之支持 Promise,并提供了对请求、响应的统一拦截功能

通过npm安装

1
2
//在项目的文件夹下
npm install axios -S

安装完后会在项目的node-modules文件夹下创建axios文件夹,和在package.json文件中导入axios依赖

快速入门

案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<template>
<div>
<input type="button" value="获取远程数据" @click="sendReq()">
</div>
</template>

<script>
// 使用前先导入
import axios from 'axios'
// axios
const option = {
methods: {
async sendReq() {
// 通过axios发送同步get请求
const resp = await axios.get("/api/students")
console.log(resp)
}
}
}
export default option
</script>

发送请求

请求 备注
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

案例

后端

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package xw.controller;

@RestController
public class AxiosController {

@GetMapping("/api/a1")
public String a1() {
return "get request";
}

@PostMapping("/api/a2")
public String a2() {
return "post request";
}

@PostMapping("/api/a3")
public String a3(@RequestHeader("Authorization") String authorization) {
System.out.println("authorization 头 " + authorization);
return "post request";
}

@PostMapping("/api/a4")
public String a4(String name, Integer age) {
System.out.println("name: " + name + " age:" + age);
return "post request";
}

@PostMapping("/api/a5")
public String a5(A5 a5) {
System.out.println(a5);
return "post request";
}

@PostMapping("/api/a5json")
public String a5json(@RequestBody A5 a5) {
System.out.println(a5);
return "post request";
}


@PostMapping("/api/a6set")
public String a6set(HttpSession session) {
System.out.println("========== a6 set ==========");
System.out.println(session.getId());
session.setAttribute("name", "张三");
return "post request";
}

@PostMapping("/api/a6get")
public String a6get(HttpSession session) {
System.out.println("========== a6 get ==========");
System.out.println(session.getId());
System.out.println("name: " + session.getAttribute("name"));
return "post request";
}


}

前端

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<template>
<div>
<input type="button" value="获取远程数据" @click="sendReq()">
</div>
</template>

<script>
// 使用前先导入
import axios from 'axios'
// axios
const option = {
methods: {
async sendReq() {
// 1.通过axios发送同步get请求
// const resp = await axios.get("/api/a1")

// 2.通过axios发送同步post请求
// const resp = await axios.post("/api/a2")

// 3.axios请求中添加请求头(url,请求体数据,选项对象)
// const resp = await axios.post("/api/a3", {}, {
// headers: {
// Authorization: 'abc'
// }
// })

// 4.1axios请求中携带参数(字符串拼接)
// const name = encodeURIComponent('!@#%$') //编码后发送
// const age = 20
// const resp = await axios.post(`/api/a4?name=${name}&age=${age}`)

// // 4.axios请求中携带参数(选项对象)
// const resp = await axios.post('/api/a4', {}, {
// params: {
// name: '!@#%$', //会自动编码
// age: 20
// }
// })

// 4.2axios请求中携带参数(请求体json)
// 请求体中的是json格式,后端是通过参数名接收,故不能直接写在参数里
// const params = new URLSearchParams() // 通过URLSearchParams封装参数
// params.append("name", "张三")
// params.append("age", 20)
// const resp = await axios.post('/api/a4', params)

// 4.3axios请求中携带参数(请求体multipart)
// const params = new FormData() // 通过FormData封装参数
// params.append("name", "张三")
// params.append("age", 21)
// const resp = await axios.post('/api/a5', params)

// 4.4axios请求中携带参数(请求体json, 后端用对象接收)
// 自动通过JSON.stringify转换为json
const resp = await axios.post('/api/a5json', {
name: '李四',
age: 21
})

console.log(resp)
}
}
}
export default option
</script>

axios配置

常见config配置

名称 含义
baseURL 将自动加在 url 前面
headers 请求头,类型为简单对象
params 跟在 URL 后的请求参数,类型为简单对象或 URLSearchParams
data 请求体,类型有简单对象、FormData、URLSearchParams、File 等
withCredentials 跨域时是否携带 Cookie 等凭证,默认为 false
responseType 响应类型,默认为 json

案例

后端

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
@RestController
//开启跨域和允许携带凭证
@CrossOrigin(value = "http://localhost:7070", allowCredentials = "true")
public class AxiosController {
@PostMapping("/api/a6set")
public String a6set(HttpSession session) {
System.out.println("========== a6 set ==========");
System.out.println(session.getId());
/*
模拟登录,将用户名存入session
*/
session.setAttribute("name", "张三");
return "post request";
}

@PostMapping("/api/a6get")
public String a6get(HttpSession session) {
System.out.println("========== a6 get ==========");
System.out.println(session.getId());
System.out.println("name: " + session.getAttribute("name"));
return "post request";
}


}

前端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<script>
// 使用前先导入
import axios from 'axios'
// axios
const option = {
methods: {
async sendReq() {
// axios配置
const _axios = axios.create({
// 会被添加在每个请求url前
baseURL: 'http://localhost:8080',
// 跨域时是否携带 Cookie 等凭证,默认为 false
withCredentials: true
})
await _axios.post('/api/a6set', {})
await _axios.post('/api/a6get', {})
}
}
}
export default option
</script>

响应格式

名称 含义
data 响应体数据 :star:
status 状态码 :star:
headers 响应头
  • 200 表示响应成功
  • 400 请求数据不正确 age=abc
  • 401 身份验证没通过
  • 403 没有权限
  • 404 资源不存在
  • 405 不支持请求方式 post
  • 500 服务器内部错误

axios拦截器

请求拦截

案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const _axios = axios.create({
// 会被添加在每个请求url前
baseURL: 'http://localhost:8080',
// 跨域时是否携带 Cookie 等凭证,默认为 false
withCredentials: true
})
// 请求拦截器
_axios.interceptors.request.use(
// 请求正常时
function (config) {
// 给每个请求都添加头Authorization
config.headers = {
Authorization: 'aaa.bbb.ccc'
}
return config
},
// 请求错误时
function (error) {
return Promise.reject(error);
}
)
_axios.get("/api/students")

响应拦截器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 响应拦截器
_axios.interceptors.response.use(
// 响应码在200之内
function (response) {
console.log('响应正常')
return response
},
// 响应码大于200时
function (error) {
if (error.response.status === 400) {
console.log('请求参数错误')
} else if (error.response.status === 500) {
console.log('服务器错误')
} else if (error.response.status === 404) {
console.log('资源未找到')
} else {
console.log('未知错误')
}
return Promise.reject(error)
}
)
_axios.get("/api/students")

可以将配置好的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
39
40
41
42
43
44
45
// axios工具类
import axios from 'axios'

// 配置
const _axios = axios.create({
baseURL: 'http://localhost:8080',
withCredentials: true
})

// 请求拦截器
_axios.interceptors.request.use(
function (config) {
config.headers = {
Authorization: 'aaa.bbb.ccc'
}
return config
},
function (error) {
return Promise.reject(error);
}
)

// 响应拦截器
_axios.interceptors.response.use(
// 响应码在200之内
function (response) {
console.log('响应正常')
return response
},
// 响应码大于200时
function (error) {
if (error.response.status === 400) {
console.log('请求参数错误')
} else if (error.response.status === 500) {
console.log('服务器错误')
} else if (error.response.status === 404) {
console.log('资源未找到')
} else {
console.log('未知错误')
}
return Promise.reject(error)
}
)

export default _axios

用的时候导入

1
2
3
4
5
6
7
8
9
10
11
12
13
<script>
// 导入自己配置好的axios
import _axios from '../utils/myaxios'
const option = {
methods: {
async sendReq() {
const resp = await _axios.get('/api/students')
console.log(resp)
}
}
}
export default option
</script>

axios API
http://xwww12.github.io/2022/10/05/前端/api/axios-API/
作者
xw
发布于
2022年10月5日
许可协议