Axios 是一个基于 Promise 的 HTTP 客户端,能够在浏览器和 Node.js 中发起 HTTP 请求。它简化了与服务器的通信,支持各种请求方法(如 GET、POST、PUT 等)以及处理请求和响应的相关操作。下面是关于 Axios 的详细学习指南。
1. 安装 Axios
在使用 Axios 之前,你需要在项目中安装它。
在浏览器中:
可以通过直接在 HTML 文件中引入 CDN 链接来使用 Axios。
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>在 Node.js 中:
通过 npm 或 yarn 安装 Axios。
npm install axios
# Axios
yarn add axios2. 基本使用方法
2.1 发起 GET 请求
GET 请求通常用于从服务器获取数据。下面是一个 GET 请求的示例。
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log(response.data); // 成功响应的数据
})
.catch(error => {
console.error(error); // 错误处理
});2.2 发起 POST 请求
POST 请求用于向服务器发送数据,例如向 API 提交表单数据。
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1
})
.then(response => {
console.log(response.data); // 成功响应的数据
})
.catch(error => {
console.error(error); // 错误处理
});2.3 使用 async/await
Axios 是 Promise 驱动的,所以可以使用 async/await 语法来简化代码。
async function fetchData() {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
console.log(response.data); // 成功响应的数据
} catch (error) {
console.error(error); // 错误处理
}
}
fetchData();3. 常见请求方法
axios.get(url, config): 发起 GET 请求。axios.post(url, data, config): 发起 POST 请求。axios.put(url, data, config): 发起 PUT 请求。axios.delete(url, config): 发起 DELETE 请求。
每种方法都会返回一个 Promise,可以通过 then 和 catch 处理响应和错误。
4. 配置请求(Config)
你可以通过 config 对象来自定义请求,常见的配置选项有:
url: 请求地址。method: 请求方法(如GET、POST)。headers: 设置 HTTP 请求头。params: 设置 URL 查询参数。data: 发送到服务器的数据(适用于POST、PUT等方法)。timeout: 请求超时时间。
示例:自定义请求配置
axios({
method: 'get',
url: 'https://jsonplaceholder.typicode.com/posts',
params: {
userId: 1
},
headers: {
'Authorization': 'Bearer token'
},
timeout: 1000 // 请求超时时间(单位:毫秒)
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});5. 处理响应
响应数据包含很多有用的信息:
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log(response.data); // 实际的响应数据
console.log(response.status); // HTTP 状态码
console.log(response.headers); // 响应头
})
.catch(error => {
console.error(error);
});6. 处理错误
Axios 提供了多种方式来处理错误,可以捕获 HTTP 错误、网络错误、超时等。
axios.get('https://jsonplaceholder.typicode.com/invalid-url')
.then(response => {
console.log(response.data);
})
.catch(error => {
if (error.response) {
// 请求已发送,但服务器返回了状态码非2xx
console.log('Error response:', error.response.data);
console.log('Error status:', error.response.status);
} else if (error.request) {
// 请求已发出,但没有收到响应
console.log('Error request:', error.request);
} else {
// 其他错误
console.log('Error message:', error.message);
}
});7. 请求和响应拦截器
Axios 提供了拦截器功能,允许在请求或响应发送之前对它们进行处理。这对于处理全局错误、自动添加身份验证令牌等非常有用。
请求拦截器:
axios.interceptors.request.use(config => {
// 在发送请求之前可以做一些处理,比如添加 token
config.headers.Authorization = 'Bearer token';
return config;
}, error => {
// 处理请求错误
return Promise.reject(error);
});响应拦截器:
axios.interceptors.response.use(response => {
// 处理响应数据
return response;
}, error => {
// 处理响应错误
return Promise.reject(error);
});8. 取消请求
使用 CancelToken 可以取消请求,适用于取消重复请求或当用户离开页面时取消挂起的请求。
const CancelToken = axios.CancelToken;
let cancel;
axios.get('https://jsonplaceholder.typicode.com/posts', {
cancelToken: new CancelToken(function executor(c) {
cancel = c; // 保存取消函数
})
})
.catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// 处理错误
}
});
// 随时调用取消请求
cancel('Operation canceled by the user.');9. Axios 实例
你可以创建 Axios 实例来配置多个请求的通用设置(如 base URL、headers 等)。
const apiClient = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
apiClient.get('/posts/1').then(response => {
console.log(response.data);
});10. 并发请求
可以使用 axios.all 和 axios.spread 来处理并发请求。
axios.all([
axios.get('https://jsonplaceholder.typicode.com/posts/1'),
axios.get('https://jsonplaceholder.typicode.com/posts/2')
])
.then(axios.spread((response1, response2) => {
console.log(response1.data);
console.log(response2.data);
}));总结
- 基础:熟悉基本的请求方法(GET、POST、PUT、DELETE)。
- 配置:利用
config自定义请求,包括设置 headers、params 等。 - 拦截器:通过请求和响应拦截器实现全局的处理,比如身份验证、错误处理等。
- 取消请求:学会使用
CancelToken取消不必要的请求。 - 并发请求:通过
axios.all处理多个并发请求。
通过学习这些内容,你就可以灵活运用 Axios 发起 HTTP 请求了!
问:async/await有什么用
async/await 是 ES2017 (ES8) 引入的 JavaScript 语法,用于处理异步操作,提供了更简单、更可读的方式来处理 Promises。相比于传统的 .then() 和 .catch() 链式处理,async/await 使异步代码的编写更加像同步代码,提高了代码的可读性和维护性。
1. 基本概念
async:用于定义一个异步函数,返回一个 Promise。异步函数允许在其中使用await关键字。await:只能在async函数中使用,等待一个 Promise 完成,并暂停函数执行,直到 Promise 解决(resolve)或拒绝(reject)。
2. 使用示例
2.1 用法示例
// 定义异步函数
async function fetchData() {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
console.log(response.data); // 在 Promise resolve 后输出结果
} catch (error) {
console.error('Error fetching data:', error); // 捕获错误
}
}
// 调用异步函数
fetchData();解释:
async function fetchData():定义一个异步函数fetchData。await axios.get(...):等待axios.get()返回的 Promise 解析后,将结果赋值给response,然后继续执行后面的代码。try...catch:用于处理可能的错误,代替.catch()。
2.2 与 Promise 的对比
使用 Promise 和 .then() 方法处理异步请求:
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});使用 async/await 处理相同的请求:
async function fetchData() {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
console.log(response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
}区别:
async/await代码看起来更像同步代码,更加直观易读。then/catch使用链式调用,可能会导致 "回调地狱" 或让代码难以理解。
3. 优势
3.1 简化代码结构
在不使用 async/await 的情况下,代码中常常需要嵌套多个 .then() 来处理多个异步操作:
axios.get('/user')
.then(response => {
return axios.get(`/user/${response.data.id}/posts`);
})
.then(postsResponse => {
console.log(postsResponse.data);
})
.catch(error => {
console.error(error);
});使用 async/await,代码变得更加平直和直观:
async function getUserPosts() {
try {
const userResponse = await axios.get('/user');
const postsResponse = await axios.get(`/user/${userResponse.data.id}/posts`);
console.log(postsResponse.data);
} catch (error) {
console.error(error);
}
}3.2 错误处理更方便
使用 async/await 可以在一个 try...catch 块中捕获所有可能的错误,而不需要为每个 .then() 调用单独处理错误:
async function getData() {
try {
const response1 = await axios.get('/data1');
const response2 = await axios.get('/data2');
console.log(response1, response2);
} catch (error) {
console.error('Error fetching data:', error);
}
}在 then/catch 中,你可能需要为每个异步请求分别处理错误,导致代码重复。
4. 处理并发请求
当你需要同时执行多个异步操作时,async/await 和 Promise.all 搭配使用,可以处理并发请求:
async function fetchMultipleData() {
try {
const [response1, response2] = await Promise.all([
axios.get('https://jsonplaceholder.typicode.com/posts/1'),
axios.get('https://jsonplaceholder.typicode.com/posts/2')
]);
console.log(response1.data, response2.data);
} catch (error) {
console.error('Error fetching data:', error);
}
}解释:
Promise.all接受一个数组,数组中的所有 Promise 都会并发执行,只有当所有 Promise 解决(resolve)后,才会继续执行await之后的代码。- 这比逐个
await执行请求更高效。
5. 注意事项
5.1 await 只能在 async 函数中使用
如果在非 async 函数中使用 await,会导致语法错误。
function fetchData() {
const data = await axios.get('/some-url'); // 会报错
}解决方法是将函数标记为 async:
async function fetchData() {
const data = await axios.get('/some-url'); // 正确使用
}5.2 阻塞代码执行
虽然 async/await 看起来像同步代码,但它本质上还是异步的。await 会暂停函数的执行,直到 Promise 被解决(resolved),这意味着如果一个异步操作耗时较长,它会阻塞后续代码的执行。因此,使用时要注意避免长时间阻塞。
async function slowOperation() {
await new Promise(resolve => setTimeout(resolve, 3000)); // 阻塞3秒
console.log('Operation complete!');
}
slowOperation();
console.log('This will be logged after 3 seconds'); // 3秒后才执行5.3 错误处理
尽量使用 try...catch 来捕获 await 操作中可能发生的错误。如果没有捕获,错误可能会被静默忽略,导致调试困难。
async function fetchData() {
try {
const response = await axios.get('/non-existent-url');
console.log(response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
}总结
- 简洁性:
async/await使异步代码更加简洁直观,接近同步代码的结构,避免回调地狱。 - 错误处理:可以使用
try...catch统一处理异步操作中的错误。 - 性能:与
Promise.all结合,可以并发执行多个异步任务,提升性能。
通过 async/await,你可以更加清晰地组织异步代码,并提高代码的可维护性和可读性。

