Axios入门
# Axios 入门
官方文档:起步 | Axios 中文文档 | Axios 中文网 (axios-http.cn) (opens new window)
# 一、Axios 是什么?
Axios 是一个基于 promise (opens new window) 网络请求库,作用于 node.js
(opens new window) 和浏览器中。
- 它是 同构性(isomorphic) (opens new window) 的(即同一套代码可以运行在浏览器和 node.js 中),极大简化了跨平台网络请求的开发流程。。
- 在服务端它使用原生 node.js
http
模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。 - 我们通常使用
axios
来发请求,它就像后端的RestTemplate
或HttpClient
,功能非常强大且易用。
在 Java 后端开发中,我们写的是接口(Controller),前端通过 HTTP 请求来调用。
现在写前端,就要反过来:前端发请求,请求后端接口拿数据。
# 二、Axios 安装与引入
# 1. 安装(在项目根目录执行)
npm install axios
1
# 2. 项目中引入
在 Vue3 项目中,你可以在某个模块中统一封装 axios(后文会讲),也可以直接使用:
import axios from 'axios';
1
# 三、基本使用示例
# 1. GET 请求(带参数)
axios.get('https://api.example.com/users', {
params: { page: 1, size: 10 }
}).then(res => {
console.log(res.data);
});
1
2
3
4
5
2
3
4
5
# 2. POST 请求(发送 JSON)
axios.post('https://api.example.com/login', {
username: 'admin',
password: '123456'
}).then(res => {
console.log(res.data.token);
});
1
2
3
4
5
6
2
3
4
5
6
# 四、Axios 配置项(类比 Java 中请求构建器)
axios({
method: 'post',
url: '/api/user',
baseURL: 'https://api.example.com',
headers: {
Authorization: 'Bearer token',
'Content-Type': 'application/json'
},
timeout: 5000,
data: { name: 'John Doe' }
});
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 五、拦截器:统一处理 Token、响应结构
类比:Java 后端的拦截器(Filter)或 AOP。
# 1. 创建 axios 实例(推荐封装)
// src/utils/request.js
import axios from 'axios';
const http = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000
});
1
2
3
4
5
6
7
2
3
4
5
6
7
# 2. 请求拦截器:加 token
http.interceptors.request.use(config => {
const token = localStorage.getItem('token');
if (token) config.headers.Authorization = `Bearer ${token}`;
return config;
});
1
2
3
4
5
2
3
4
5
# 3. 响应拦截器:统一处理错误
http.interceptors.response.use(res => {
return res.data;
}, err => {
console.error('请求失败:', err.response?.data?.message || err.message);
return Promise.reject(err);
});
1
2
3
4
5
6
2
3
4
5
6
# 六、在 Vue3 中使用 Axios 请求数据(组合式 API)
<script setup>
import { ref, onMounted } from 'vue';
import http from '@/utils/request';
const users = ref([]);
onMounted(async () => {
try {
const res = await http.get('/users');
users.value = res.data;
} catch (e) {
console.error('加载用户失败', e);
}
});
</script>
<template>
<ul>
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
</template>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 七、封装 API 模块(推荐结构)
# 1. 创建一个用户模块 API(src/api/user.js)
import http from '@/utils/request';
export const getUserList = (params) => http.get('/users', { params });
export const login = (data) => http.post('/login', data);
1
2
3
4
2
3
4
# 2. 页面中使用
import { getUserList } from '@/api/user';
onMounted(async () => {
const res = await getUserList({ page: 1 });
console.log(res);
});
1
2
3
4
5
6
2
3
4
5
6
# 八、实战练习建议
- 调用你写的 Spring Boot 接口(比如登录、列表查询)
- 自定义封装请求模块,配置 baseURL 为你本地服务地址
- 搭配浏览器的 F12 网络工具,分析请求与响应
# 九、总结
功能 | Java 后端类比 | Axios |
---|---|---|
请求封装 | HttpClient / RestTemplate | axios.create() |
请求参数 | Map<String, Object> | params , data |
拦截器 | Filter / AOP | interceptors |
错误处理 | try-catch + 异常类 | .catch() / response 拦截 |
Bean 封装 | DTO / Service 层 | api 模块封装函数 |
上次更新: 2025/5/20 17:42:11