Axios基本使用,为学习后续的Vue服务【发送请求+并发请求+前端拦截器】

目录

1、项目中引入Axios

2、使用Axios发送请求

2.1、例:发送GET请求

2.2、例:发送POST请求

3、axios并发请求

4、拦截器


1、项目中引入Axios

复制代码
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

注:个人学习笔记,因自己学过后端,所以有关后端的代码,我在这里就不展示了~

不了解后端的宝子,也不会耽误学习,因为公司里会有写好的接口文档,直接使用就可以了

2、使用Axios发送请求

2.1、例:发送GET请求

javascript 复制代码
axios.get("http://localhost:8080/user?id=1").then(function(res) {
        console.log(res);
    }).catch(function(error){
        console.log(error);
    });
    // es6中简化写法:lambada表达式
    axios.get("http://localhost:8080/user?id=2").then((res)=> {
        console.log(res);
    }).catch((error)=> {
        console.log(error);
    });

格式其实还是挺简单的~

2.2、例:发送POST请求

javascript 复制代码
axios.post("http://localhost:8080/user",{
        name:"xxx",
        age:10
   }).then((res)=> {
        console.log(res);
    }).catch((error)=> {
        console.log(error);
    });

3、axios并发请求

并发请求:将多个请求在同一时刻发送到后端服务接口,最后在集中处理每个请求的响应结果

代码:

javascript 复制代码
function test1() {
        return axios.get("http://localhost:8080/user?id=3");
    }
    function test2() {
        return axios.get("http://localhost:8080/user?id=4");
    }
    axios.all([test1(),test2()]).then(
        axios.spread((res_test1,res_test2)=> {
            console.log(res_test1);
            console.log(res_test2);
        })
    );

4、拦截器

  • 作用:用来将axios中共有参数,响应公共处理交给拦截处理,减少axios发送请求时代码冗余
  • 类型:请求拦截器;响应拦截器

使用:

javascript 复制代码
 //创建axios的配置对象
    var instance = axios.create({
        baseURL:"http://localhost:8080/",
        timeout:5000
    });
    //请求拦截器
    instance.interceptors.request.use(function(config) {
        config.url += "?token=1111"
        return config;
    });
    //响应拦截器
    instance.interceptors.response.use(function(response) {
        if(response.status == 500) {
            alert("服务器内部故障");
        }
        return response
    });

好啦,以上就是简单的学习,简单了解一下,axios的强大之处~

后面周末会做一个简单小项目练练手,到时候再和大家分享分享~

相关推荐
锋行天下7 小时前
公司内网部署大模型的探索之路
前端·人工智能·后端
1024肥宅7 小时前
手写 EventEmitter:深入理解发布订阅模式
前端·javascript·eventbus
集3048 小时前
C++多线程学习笔记
c++·笔记·学习
知南x8 小时前
【正点原子STM32MP157 可信任固件TF-A学习篇】(2) STM32MP1 中的 TF-A
stm32·嵌入式硬件·学习·stm32mp157
YJlio8 小时前
Active Directory 工具学习笔记(10.0):AdExplorer / AdInsight / AdRestore 导读与场景地图
网络·笔记·学习
EveryPossible8 小时前
google搜索框
vue.js
子夜江寒8 小时前
Python 学习-Day8-执行其他应用程序
python·学习
海市公约9 小时前
HTML网页开发从入门到精通:从标签到表单的完整指南
前端·ide·vscode·程序人生·架构·前端框架·html
●VON9 小时前
从单机应用到分布式调度:基于 HarmonyOS 构建车-空协同任务引擎
学习·华为·harmonyos·openharmony·开源鸿蒙
万变不离其宗_89 小时前
http学习笔记
笔记·学习