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

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

相关推荐
不爱吃糖的程序媛21 分钟前
浅谈前端架构设计与工程化
前端·前端架构设计
BillKu2 小时前
Vue3 Element Plus 对话框加载实现
javascript·vue.js·elementui
郝YH是人间理想2 小时前
系统架构设计师案例分析题——web篇
前端·软件工程
Evaporator Core2 小时前
深入探索:Core Web Vitals 进阶优化与新兴指标
前端·windows
向上的车轮2 小时前
MATLAB学习笔记(七):MATLAB建模城市的雨季防洪排污的问题
笔记·学习·matlab
初遇你时动了情3 小时前
html js 原生实现web组件、web公共组件、template模版插槽
前端·javascript·html
QQ2740287563 小时前
Soundness Gitpod 部署教程
linux·运维·服务器·前端·chrome·web3
前端小崔3 小时前
从零开始学习three.js(18):一文详解three.js中的着色器Shader
前端·javascript·学习·3d·webgl·数据可视化·着色器
哎呦你好3 小时前
HTML 表格与div深度解析区别及常见误区
前端·html
运维@小兵3 小时前
vue配置子路由,实现点击左侧菜单,内容区域显示不同的内容
前端·javascript·vue.js