Axios 是一个基于 Promise 的 HTTP 库,它可以在浏览器和 Node.js 中使用。Axios 可以让我们更容易地进行 HTTP 请求并处理服务器响应。
安装
你可以使用 npm 或 yarn 来安装 Axios:
npm install axios # 或者 yarn add axios
发送请求
Axios 提供了多种发送请求的方法,包括 GET、POST、PUT、DELETE 等等。下面是几个常用的例子:
GET 请求
axios.get('/api/users')
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});POST 请求
-- -------------------- ---- -------
------------------------ -
---------- -------
--------- -----
--
-------------- ---------- -
----------------------
--
--------------- ------- -
-------------------
---PUT 请求
-- -------------------- ---- -------
--------------------------- -
---------- -------
--------- -----
--
-------------- ---------- -
----------------------
--
--------------- ------- -
-------------------
---DELETE 请求
axios.delete('/api/users/123')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});请求配置
Axios 还提供了一些请求配置选项,例如超时时间、请求头等等。下面是一个例子:
-- -------------------- ---- -------
-------
------- -------
---- -------------
----- -
---------- -------
--------- -----
--
-------- -
------------------- ----------------
--
-------- ----
--
-------------- ---------- -
----------------------
--
--------------- ------- -
-------------------
---在上面的例子中,我们设置了请求方法、URL、请求体、请求头和超时时间等配置选项。
拦截器
Axios 还提供了拦截器,可以在发送请求和接收响应时进行拦截和处理。下面是一个例子:
-- -------------------- ---- ------- -- ------- --------------------------------------- -------- - -- ----------- --------------------- ------ ------- -- -------- ------- - -- --------- ------ ---------------------- --- -- ------- ---------------------------------------- ---------- - -- --------- --------------------- ------ --------- -- -------- ------- - -- --------- ------ ---------------------- ---
在上面的例子中,我们使用 use 方法添加了请求和响应拦截器,并在拦截器中输出了一些信息。
错误处理
当请求失败时,Axios 会返回一个错误对象。你可以在 catch 方法中对这个错误进行处理,例如输出错误信息或者进行重试等等。
-- -------------------- ---- -------
-----------------------
-------------- ---------- -
---------------------------
--
--------------- ------- -
-- ---------------- -
-- ------------------
---------------------------------
-----------------------------------
------------------------------------
- ---- -- --------------- -
-- --------------
---------------------------
- ---- -
-- -------------------
-------------------- ---------------
-
--------------------------
---在上面的例子中,我们对错误对象进行了区分和处理,并输出了一些相关的信息。
总结
Axios 是一个非常方便的 HTTP 库,它提
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/32201