一、Axios 是什么?
Axios 是可以发出 http 请求的 JavaScript 库,在 浏览器 和 node.js 环境中都可以运行。
二、axios 与 fetch 的区别
1、相同点:
- 都是可以发出 http 请求的 JavaScript 库。
2、不同点
- fetch 是 JavaScript 原生库,浏览器都支持,无需安装直接使用;axios 不是原生库,需要安装才能使用;
- fetch 只能在浏览器环境中运行;axios 既可以在浏览器、也可以在node.js 环境中运行。
3、其他
- 如果是 node.js 项目,优先选择使用 axios.
三、安装 axios
npm install axios
# 或
yarn add axios
四、第一种使用方法
直接调用 axios 提供的 get 或 post 方法 发出 http 请求。
1、GET 请求
-
两种使用方式
const axios = require('axios'); // 1、向给定ID的用户发起请求 axios.get('/user?ID=12345') .then(function (response) { // 处理成功情况 console.log(response); }) .catch(function (error) { // 处理错误情况 console.log(error); }) .then(function () { // 总是会执行 }); // 2、上述请求也可以按以下方式完成(可选) axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { // 总是会执行 });
-
支持async/await用法
const axios = require('axios'); async function getUser() { try { const response = await axios.get