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的强大之处~

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

相关推荐
前端百草阁3 分钟前
JavaScript 设计模式(23 种)
开发语言·前端·javascript·设计模式
用户69371750013848 分钟前
AI 领域的 Harness,到底是什么意思?
android·前端·后端
spider_xcxc14 分钟前
Redis 深度实践:安全管控、性能压测与持久化分析(二)
运维·前端·redis·云计算·bootstrap·运维开发
乘风gg14 分钟前
代码都已经让 AI 写了,为什么有些人却更慌了?
前端·ai编程·claude
我不是外星人25 分钟前
一键还原任意网站,这套 Playwright + 多 Agent 工程流太猛了
前端·后端·ai编程
用户0595401744629 分钟前
AI 客服突然“失忆”,排查 6 小时发现 LangChain 记忆存储的 3 个致命坑
前端·css
IT_陈寒1 小时前
Vue的v-if和v-show,我竟然用错了这么久
前端·人工智能·后端
云絮.1 小时前
计算机相关工作原理
服务器·前端·数据库
随风一样自由1 小时前
【前端+React+缓存竞态】导航切换缓存刷新机制
前端·react.js·缓存
恋猫de小郭1 小时前
Flutter 开发怎么做 Agent ?从工程实战详细给你解读下
android·前端·flutter