axios学习

Axios 是一个基于 Promise 的 HTTP 客户端,用于浏览器和 node.js。它提供了一种简单的方法来发送异步 HTTP 请求到 REST 端点并处理响应。以下是 Axios 学习的详细指南:

一、Axios 的介绍

1. 定义与原理
  • 定义:Axios 是一个基于 Promise 的 HTTP 客户端,用于浏览器和 node.js。
  • 原理:Axios 在浏览器端使用 XMLHttpRequests,在 node.js 中使用 http 模块进行通信。它封装了这些底层技术,提供了更加易用和灵活的 API。
2. 特性
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换 JSON 数据
  • 客户端支持防御 XSRF(跨站请求伪造)
3. 浏览器支持

Axios 支持所有现代浏览器,包括 Firefox、Chrome、Safari、Opera、Edge 以及 IE8+。

二、安装 Axios

Axios 可以通过多种方式安装,包括 npm、bower、yarn 以及通过 CDN 引入。

  • npm 安装npm install axios
  • bower 安装bower install axios
  • yarn 安装yarn add axios
  • CDN 引入
    • <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    • <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

三、Axios 的基本用法

1. 引入 Axios

在需要使用 Axios 的文件中,通过 import 或 require 引入 Axios。

import axios from 'axios';  
// 或者  
const axios = require('axios');
2. 发送 GET 请求
axios.get('/user?ID=12345')  
  .then(function (response) {  
    // 处理成功情况  
    console.log(response);  
  })  
  .catch(function (error) {  
    // 处理错误情况  
    console.log(error);  
  })  
  .then(function () {  
    // 总是会执行  
  });  
  
// 或者使用 async/await  
async function getUser() {  
  try {  
    const response = await axios.get('/user?ID=12345');  
    console.log(response.data);  
  } catch (error) {  
    console.error(error);  
  }  
}  
  
getUser();
3. 发送 POST 请求
axios.post('/user', {  
    firstName: 'Fred',  
    lastName: 'Flintstone'  
  })  
  .then(function (response) {  
    console.log(response);  
  })  
  .catch(function (error) {  
    console.log(error);  
  });  
  
// 或者使用 async/await  
async function createUser() {  
  try {  
    const response = await axios.post('/user', {  
      firstName: 'Fred',  
      lastName: 'Flintstone'  
    });  
    console.log(response.data);  
  } catch (error) {  
    console.error(error);  
  }  
}  
  
createUser();
4. 发送其他类型的请求(PUT、DELETE 等)
axios.put('/user/12345', {  
  firstName: 'Fred',  
  lastName: 'Flintstone'  
})  
.then(function (response) {  
  console.log(response);  
})  
.catch(function (error) {  
  console.log(error);  
});  
  
axios.delete('/user/12345')  
.then(function (response) {  
  console.log(response);  
})  
.catch(function (error) {  
  console.log(error);  
});

欢迎欢迎!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值