Axios
Axios
Axios 简介
Axios 是基于 Promise 的 HTTP 请求库,支持浏览器和 Node.js 环境,提供简洁的 API 用于发送 GET、POST、PUT、DELETE 等请求,是前端工程化项目的首选 HTTP 工具(使用率超 99%)。
Promise
Promise 是 JavaScript 中处理异步操作的对象,代表一个尚未完成但未来会结束的操作,有三种核心状态:
| 状态 | 描述 | 对应回调方法 |
|---|---|---|
| pending | 进行中(初始状态) | - |
| resolve | 操作成功 | then() |
| rejected | 操作失败 | catch() |
Promise 核心方法
then(result):接收成功结果,处理成功逻辑catch(error):接收失败原因,处理异常逻辑(可省略)finally():无论成功/失败,最终都会执行all(promises):等待多个 Promise 全部完成后再执行
基础语法
const promise = new Promise((resolve, reject) => {
// 异步操作(如 HTTP 请求、定时器)
const success = true;
if (success) {
resolve("操作成功的结果"); // 成功时调用,触发 then()
} else {
reject("操作失败的原因"); // 失败时调用,触发 catch()
}
});
promise.then(result => {
console.log("成功:", result);
}).catch(error => {
console.log("失败:", error);
}).finally(() => {
console.log("操作结束(无论成败)");
});
Axios 常用请求示例
引入 Axios
通过 CDN 直接引入(适合非工程化项目):
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
GET 请求(查询数据)
两种参数传递方式,推荐第二种(避免拼接错误):
// 方式 1:直接拼接参数(不推荐,易出错)
function sendGet1() {
axios.get(`https://localhost/hippo/user/exist?username=peppa`)
.then(response => {
console.log('GET 请求成功:', response.data); // response.data 为后端返回数据(默认 JSON 格式)
})
.catch(error => {
console.log('GET 请求失败:', error);
});
}
// 方式 2:通过 params 传递参数(推荐,自动处理特殊字符)
function sendGet2() {
axios.get(`https://localhost/hippo/user/exist`, {
params: {
username: 'peppa',
password: '123456' // 参数值含 & 等特殊字符时会自动转义
}
})
.then(response => {
console.log('GET 请求成功:', response.data);
})
.catch(error => {
console.log('GET 请求失败:', error);
});
}
POST 请求(提交数据)
支持两种数据格式:JSON 格式(默认)和表单格式。
JSON 格式(推荐,前后端分离常用)
function sendPost() {
const user = {
username: 'peppa',
password: '123456'
};
axios.post(`https://localhost/hippo/user/register`, user)
.then(response => {
console.log('POST 请求成功:', response.data);
});
}
Java 后端接收 JSON 数据:
String json = "";
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
json += line;
}
// 将 JSON 转为 User 对象(需引入 FastJSON 等工具包)
User user = JSONObject.parseObject(json, User.class);
// 业务逻辑...
表单格式(application/x-www-form-urlencoded)
function sendPostForm() {
const params = new URLSearchParams();
params.append('username', 'peppa');
params.append('password', '123456');
axios.post(`https://localhost/hippo/user/register`, params)
.then(response => {
console.log('表单提交成功:', response.data);
});
}
Java 后端接收表单数据:
String username = request.getParameter("username");
String password = request.getParameter("password");
// 业务逻辑...
PUT 请求(更新数据)
function sendPut() {
const user = {
id: 1, // 需更新数据的唯一标识
username: 'peppa',
password: '654321' // 新密码
};
axios.put(`https://localhost/hippo/user/update`, user)
.then(response => {
console.log('PUT 请求成功:', response.data);
});
}
DELETE 请求(删除数据)
function sendDelete() {
axios.delete(`https://localhost/hippo/user/delete`, {
params: {
username: 'peppa' // 删除条件参数
}
})
.then(response => {
console.log('DELETE 请求成功:', response.data);
});
}
同步请求(async/await 语法)
通过 async/await 简化 Promise 回调,让异步代码更像同步代码:
async function sendGetSync() {
try {
// 等待请求完成,直接获取 data(解构赋值并重命名)
const { data: response } = await axios.get(`https://localhost/hippo/user/find?id=1`);
console.log('同步请求成功:', response);
console.log('数据类型:', typeof response);
} catch (error) {
// 异常捕获(替代 catch() 方法)
console.log('同步请求失败:', error);
}
}
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>axios</title>
<!-- 引入axios库,用于完成http请求 -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<button onclick="sendGet1()">get-simple</button> <br />
<button onclick="sendGet2()">get-multi</button> <br />
<button onclick="sendPost()">post-default(json)</button> <br />
<button onclick="sendPostForm()">post-form</button> <br />
<button onclick="sendPut()">put</button> <br />
<button onclick="sendDelete()">delete</button>
<script>
// get请求,查
function sendGet1() {
axios.get(`https://localhost/hippo/user/exist?username=peppa`).then(response => {
console.log('请求成功,data:', response)
}).catch(error => { // 如果异常错误不处理可以省略
console.log('请求失败,cause:', error)
})
}
// 请求参数避免拼接错误
function sendGet2() {
axios.get(`https://localhost/hippo/user/exist`, {
params: {
username: 'peppa', // 参数名+参数值
password: '123456'
} // 避免拼接出现的错误(例如参数值中有&导致出现问题,值中若有&会自动帮助转换)
}).then(response => {
console.log('请求成功,data:', response)
}).catch(error => { // 如果异常错误不处理可以省略
console.log('请求失败,cause:', error)
})
}
// post请求,增
function sendPost() {
let user = {
username: 'peppa',
password: '123456'
}
axios.post(`https://localhost/hippo/user/register`, user).then(response => {
console.log('请求成功,data:', response)
console.log(response.data) // 获取 promise 中的 data 属性(后端返回的数据,默认时 json 格式)
})
}
/*
传递的是 json 格式的数据
Java 后端获取 json 数据为:
String json = null;
var reader = request.getReader();
while((json = reader.readLine()) != null) {
json += reader.readLine();
}
// 可以将json数据转为对象
// 先判断 json 是否为空
...
// 将json转为对象,假设对象类为 User
var user = JSONObject.parse(json, User.class);
// 业务逻辑
...
会先发送域检请求,再发送post请求
故需要重写 doOptions() 方法,设置允许跨域请求
@Override
protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 允许跨域
resp.setHeader("Access-Control-Allow-Origin", "*"); // * 表示所有域名都可以访问
resp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); // 允许某些方法访问
resp.setHeader("Access-Control-Allow-Headers", "Content-Type"); // 允许某些请求头访问
resp.setHeader("Access-Control-Max-Age", "3600"); // 缓存时间,这一段时间里面不需要再次访问是否允许跨域
}
*/
// post请求表单
function sendPostForm() {
// 请求体参数格式
let params = new URLSearchParams() // 这样传递的参数就不是json格式,而是表单数据格式
params.append('username', 'peppa')
params.append('password', 'peppa')
axios.post(`https://localhost/hippo/user/register`, params).then(response => {
console.log('请求成功,data:', response)
})
}
/*
Java后端获取表单数据为:
String username = request.getParameter("username");
String password = request.getParameter("password");
// 业务逻辑
...
*/
// put请求,改
function sendPut() {
let user = {
id: 1,
username: 'peppa',
password: '123456'
}
axios.put(`https://localhost/hippo/user/register`, user).then(response => {
console.log('请求成功,data:', response)
})
}
// delete请求,删
function sendDelete() {
let user = {
username: 'peppa',
password: '123456'
}
axios.delete(`https://localhost/hippo/user/register`, user).then(response => {
console.log('请求成功,data:', response)
})
}
// 同步请求
async function sendGet() {
// 同步等待异步请求返回结果(promise),从promise中解构处 data 属性,重命名为 response
const {data: response} = await axios.get(`https://localhost/hippo/user/find?id=1`)
console.log('请求成功,data:', response)
console.log(typeof response)
}
</script>
</body>
</html>

浙公网安备 33010602011771号