axios使用笔记

文章目录

  • 基本语法
  • 其他语法
  • defaults config
    • 作用
    • 案例
  • 创建实例对象
    • 作用
    • 案例
  • 拦截器 interceptor(AOP)
  • 请求取消(节流)

基本语法

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>axios基本使用</title>
    <link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
    <div class="container">
        <h2 class="page-header">基本使用</h2>
        <button class="btn btn-primary"> 发送GET请求 </button>
        <button class="btn btn-warning" > 发送POST请求 </button>
        <button class="btn btn-success"> 发送 PUT 请求 </button>
        <button class="btn btn-danger"> 发送 DELETE 请求 </button>
    </div>
    <script>
        //获取按钮
        const btns = document.querySelectorAll('button');

        //第一个
        btns[0].onclick = function(){
            //发送 AJAX 请求
            axios({
                //请求类型
                method: 'GET',
                //URL
                url: 'http://localhost:3000/posts/2',
            }).then(response => {
                console.log(response);
            });
        }

        //添加一篇新的文章
        btns[1].onclick = function(){
            //发送 AJAX 请求
            axios({
                //请求类型
                method: 'POST',
                //URL
                url: 'http://localhost:3000/posts',
                //设置请求体
                data: {
                    title: "今天天气不错, 还挺风和日丽的",
                    author: "张三"
                }
            }).then(response => {
                console.log(response);
            });
        }

        //更新数据
        btns[2].onclick = function(){
            //发送 AJAX 请求
            axios({
                //请求类型
                method: 'PUT',
                //URL
                url: 'http://localhost:3000/posts/3',
                //设置请求体
                data: {
                    title: "今天天气不错, 还挺风和日丽的",
                    author: "李四"
                }
            }).then(response => {
                console.log(response);
            });
        }

        //删除数据
        btns[3].onclick = function(){
            //发送 AJAX 请求
            axios({
                //请求类型
                method: 'delete',
                //URL
                url: 'http://localhost:3000/posts/3',
            }).then(response => {
                console.log(response);
            });
        }

    </script>
</body>

</html>

其他语法

与基本语法没什么区别,使用基本语法即可

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>axios其他使用</title>
    <link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
    <div class="container">
        <h2 class="page-header">其他使用</h2>
        <button class="btn btn-primary"> 发送GET请求 </button>
        <button class="btn btn-warning" > 发送POST请求 </button>
        <button class="btn btn-success"> 发送 PUT 请求 </button>
        <button class="btn btn-danger"> 发送 DELETE 请求 </button>
    </div>
    <script>
        //获取按钮
        const btns = document.querySelectorAll('button');

        //发送 GET 请求
        btns[0].onclick = function(){
            // axios()
            axios.request({
                method:'GET',
                url: 'http://localhost:3000/comments'
            }).then(response => {
                console.log(response);
            })
        }

        //发送 POST 请求
        btns[1].onclick = function(){
            // axios()
            axios.post(
                'http://localhost:3000/comments', 
                {
                    "body": "喜大普奔",
                    "postId": 2
                }).then(response => {
                    console.log(response);
                })
        }

        /**
         * axios({
         *      url: '/post',
         *      //  /post?a=100&b=200
         *      //  /post/a/100/b/200
         *      //  /post/a.100/b.200
         *      params: {
         *          a:100,
         *          b:200
         *      }
         * })
         * 
         * 
         *  
         */

    </script>
</body>

</html>

defaults config

作用

解耦,用于生产环境和测试环境,默认配置生产环境即可,测试环境url写在vuex的全局变量里面

案例

<body>
    <div class="container">
        <h2 class="page-header">基本使用</h2>
        <button class="btn btn-primary"> 发送GET请求 </button>
        <button class="btn btn-warning" > 发送POST请求 </button>
        <button class="btn btn-success"> 发送 PUT 请求 </button>
        <button class="btn btn-danger"> 发送 DELETE 请求 </button>
    </div>
    <script>
        //获取按钮
        const btns = document.querySelectorAll('button');
        //默认配置
        axios.defaults.method = 'GET';//设置默认的请求类型为 GET
        axios.defaults.baseURL = 'http://localhost:3000';//设置基础 URL
        axios.defaults.params = {id:1};
        axios.defaults.timeout = 3000;

        btns[0].onclick = function(){
            axios({
                url: '/posts'
            }).then(response => {
                console.log(response);
            })
        }

    </script>
</body>

创建实例对象

作用

解耦
在这里插入图片描述

案例

在这里插入图片描述

拦截器 interceptor(AOP)

在这里插入图片描述
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拦截器</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
    <script>
        // Promise
        // 设置请求拦截器  config 配置对象
        axios.interceptors.request.use(function (config) {
            console.log('请求拦截器 成功 - 1号');
            //修改 config 中的参数
            config.params = {a:100};

            return config;
        }, function (error) {
            console.log('请求拦截器 失败 - 1号');
            return Promise.reject(error);
        });

        axios.interceptors.request.use(function (config) {
            console.log('请求拦截器 成功 - 2号');
            //修改 config 中的参数
            config.timeout = 2000;
            return config;
        }, function (error) {
            console.log('请求拦截器 失败 - 2号');
            return Promise.reject(error);
        });

        // 设置响应拦截器
        axios.interceptors.response.use(function (response) {
            console.log('响应拦截器 成功 1号');
            return response.data;
            // return response;
        }, function (error) {
            console.log('响应拦截器 失败 1号')
            return Promise.reject(error);
        });

        axios.interceptors.response.use(function (response) {
            console.log('响应拦截器 成功 2号')
            return response;
        }, function (error) {
            console.log('响应拦截器 失败 2号')
            return Promise.reject(error);
        });

        //发送请求
        axios({
            method: 'GET',
            url: 'http://localhost:3000/posts'
        }).then(response => {
            console.log('自定义回调处理成功的结果');
            console.log(response);
        });
    </script>   
</body>
</html>

请求取消(节流)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>取消请求</title>
    <link crossorigin='anonymous' href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
    <div class="container">
        <h2 class="page-header">axios取消请求</h2>
        <button class="btn btn-primary"> 发送请求 </button>
        <button class="btn btn-warning" > 取消请求 </button>
    </div>
    <script>
        //获取按钮
        const btns = document.querySelectorAll('button');
        //2.声明全局变量
        let cancel = null;
        //发送请求
        btns[0].onclick = function(){
            //检测上一次的请求是否已经完成,如果没有,则取消上次请求
            if(cancel !== null){
                //取消上一次的请求
                cancel();
            }
            axios({
                method: 'GET',
                url: 'http://localhost:3000/posts',
                //1. 添加配置对象的属性
                cancelToken: new axios.CancelToken(function(c){
                    //3. 将 c 的值赋值给 cancel
                    cancel = c;
                })
            }).then(response => {
                console.log(response);
                //将 cancel 的值初始化
                cancel = null;
            })
        }

        //绑定第二个事件取消请求
        btns[1].onclick = function(){
            cancel();
        }
    </script>   
</body>
</html>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/16567.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

可视化工作流管理

​本场景是可视化工作流&#xff0c;通过可视化的精益看板将价值流进行可视化&#xff0c;通过精益思维消除瓶颈、加速流动&#xff0c;提升效率。 创建工作流任务看板 •通过Leangoo可视化工作流项目模板&#xff0c;创建一个工作流看板。 •通过看板&#xff0c;我们可以将…

「欧拉定理」[SDOI2008]仪仗队

[SDOI2008]仪仗队 https://ac.nowcoder.com/acm/problem/20313 题目描述 作为体育委员&#xff0c;C君负责这次运动会仪仗队的训练。 仪仗队是由学生组成的N * N的方阵&#xff0c;为了保证队伍在行进中整齐划一&#xff0c;C君会跟在仪仗队的左后方&#xff0c;根据其视线所…

【计算机网络】图解内容分发网络 CDN

【计算机网络】图解内容分发网络 CDN 参考资料&#xff1a; 用了CDN就一定比不用更快吗&#xff1f; 什么是内容分发网络 高性能利器&#xff1a;CDN我建议你好好学一下&#xff01; 文章目录 【计算机网络】图解内容分发网络 CDN一、CDN 概述1.1、什么是 CDN1.2、为什么需要 …

【Java笔试强训 16】

&#x1f389;&#x1f389;&#x1f389;点进来你就是我的人了博主主页&#xff1a;&#x1f648;&#x1f648;&#x1f648;戳一戳,欢迎大佬指点! 欢迎志同道合的朋友一起加油喔&#x1f93a;&#x1f93a;&#x1f93a; 目录 一、选择题 二、判断题 &#x1f525;完全数计…

shell的基础学习三

文章目录 一、Shell 流程控制二、Shell 函数三、Shell 输入/输出重定向四、Shell 文件包含总结 一、Shell 流程控制 for 循环 与其他编程语言类似&#xff0c;Shell支持for循环。 for循环一般格式为&#xff1a; while 语句 while 循环用于不断执行一系列命令&#xff0c;也…

02-Vue技术栈之基础篇(下)

目录 1、class 与 style 绑定1.1 理解1.2 class 绑定1.3 style绑定1.4 代码示例 2、条件渲染2.1 v-if2.2 v-show2.3 注意事项2.4 代码示例 3、列表渲染3.1 基本列表3.2 key的原理3.2.1 虚拟DOM中key的作用&#xff1a;3.2.2 对比规则&#xff1a;3.2.3 用index作为key可能会引发…

IPsec中IKE与ISAKMP过程分析(主模式-消息1)

IPsec协议族中IKE&#xff08;Internet Key Exchange&#xff09;是一种基于ISAKMP的协议&#xff0c;它为建立IPSec安全通信隧道提供了一种无痕密钥交换的机制。简单来说&#xff0c;IKE就是ISAKMP的扩展&#xff0c;为ISAKMP提供了更加高效、灵活和安全的密钥协商机制。 GMT …

ChatGPT实现HTML网页文本提取

网页自动化工具 既然ChatGPT对于编程语言有非常强大的理解能力&#xff0c;那么它是否可以用来自动化地处理网页呢&#xff1f;答案是肯定的。ChatGPT可以使用机器学习算法来识别网页元素中的文本&#xff0c;并抽取出有用的信息。 例如我们提供一段层数比较多的相对来说较为…

继续科普:ChatGPT 最新写论文使用方法

这两天发现了几个国内就能用的ChatGPT,不需要魔法! 给大家推荐两种方法,大家自行选择: 1、电脑端安装VSCode软件,使用GPT插件: 优点: 无需魔法、无需付费、软件简单易用(稍懂电脑就会用) 缺点: ① 只支持电脑端,不支持手机:软件安装虽简单,但不一定所有人都…

java基础知识——22.lambda表达式

这篇文章&#xff0c;我们来讲一下java的lambda表达式 目录 1.初识lambda表达式 2.lambda表达式介绍 2.1 函数式编程 2.2 lambda表达式的具体格式 2.3 Lambda表达式的好处 2.4 Lambda的省略写法 1.初识lambda表达式 首先&#xff0c;我们来看一下lambda表达式的应用 下…

CKA/CKS/CKAD认证考试攻略

什么是CKA考试&#xff1f; CKA认证考试是由Linux基金会和云原生计算基金会(CNCF)创建的&#xff0c;以促进Kubernetes生态系统的持续发展。该考试是一种远程在线、有监考、基于实操的认证考试&#xff0c;需要在运行Kubernetes的命令行中解决多个任务。CKA认证考试是专为Kube…

SpringCloud+RabbitMQ+Docker+Redis+搜索+分布式,系统详解springcloud微服务技术栈

Docker 我们发现在微服务中有一个令人头疼的问题——部署&#xff0c;用Docker去解决这个部署难题 &#xff08;一&#xff09;初识Docker-什么是docker 1、项目部署的问题 2、Docker 扔到一台机器上&#xff0c;它们的依赖难道没有干扰吗&#xff1f;不会&#xff0c;docke…

组合导航卡尔曼滤波几个杂项

1.组合导航卡尔曼滤波噪声协方差矩阵调参 在组合导航卡尔曼滤波算法中&#xff0c;主要涉及两个噪声协方差矩阵&#xff0c;过程噪声协方差矩阵Q&#xff0c;测量噪声协方差矩阵R&#xff0c;具体来说&#xff1a; R表示测量噪声协方差&#xff0c;它是一个数值&#xff0c;这…

低代码平台很赞,用2个小时,搭出1套应用

最近低代码很火&#xff0c;到处都是低代码的尝试贴&#xff0c;笔者今天也决定深入体验一下&#xff0c;感受它的便捷程度。 在案例开始之前&#xff0c;我们先来聊聊概念。 一、低代码 低代码实质上并不是一个新颖的话题&#xff0c;也不是最近才有的技术突破和创新&#xf…

【全年汇总】2023年CCF软件工程/系统软件/程序设计语言会议截稿时间汇总(持续更新)

本博文是根据CCF会议推荐的软件工程/系统软件/程序设计语言领域相关会议目录撰写。 一、截稿时间总览 截稿时间的总时间轴内容将会持续更新...... 往年投稿及录用情况及链接详见图片后面的内容。 二、会议详细目录 由于一些会议的投稿时间还没公开&#xff0c;因此根据往年投稿…

gRPC结合vcpkg在x64-windows平台visual studio2019 cmake工程里面的应用

这里我们运用vcpkg去下载安装gRPC&#xff0c;进入vcpkg目录后&#xff0c;执行命令&#xff1a;.\vcpkg.exe install grpc:x64-windows grpc在vcpkg里面安装完成后&#xff0c;我们就来使用grpc做一个简单的例子。 gRPC顾名思义&#xff0c;就是google的RPC方案&#xff0c;…

4月23日作业

#include <iostream> #include <cstring> using namespace std; class Student //学生类 { private: string name; //姓名 int year; //年龄 double sorce; //分数 public: Student (){} //无参构造 Student(string a,int b,double c):name(a),y…

元宇宙营销策略、玩法与案例

“元宇宙”依旧是当下品牌创新营销的重要形式&#xff0c;从时趣的行业观察来看&#xff0c;大量品牌方都有着元宇宙的营销意向&#xff0c;但在营销落地上存在不同的进度。一个显而易见的事实是&#xff0c;元宇宙不仅仅是一个虚拟的游戏空间&#xff0c;更是一个未来人人都会…

Java 抽象类和接口

一、抽象类和接口定义和使用场景 当你需要设计一些类&#xff0c;这些类有一些属性和方法是可以共享的&#xff0c;但同时又有一些属性和方法是需要不同的。在这种情况下&#xff0c;Java中提供了两种不同的机制&#xff0c;即“抽象类”和“接口”。 抽象类是一个类&#xff0…

第二十一章 光源

光源是每个场景必不可少的部分&#xff0c;光源除了能够照亮场景之外&#xff0c;还可以产生阴影效果。 Unity中分为四种光源类型&#xff1a; 1. 方向光&#xff1a;Directional Light 用于模拟太阳光&#xff0c;方向光任何地方都能照射到。 2. 点光源&#xff1a;Point L…
最新文章