axios使用笔记

news2024/10/1 9:37:52

文章目录

  • 基本语法
  • 其他语法
  • 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.coloradmin.cn/o/485151.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

ADRC自抗扰算法优化(PLC梯形图篇)

ADRC自抗扰算法PLC梯形图完整源代码请参看下面博客文章: ADRC自抗扰控制算法(含梯形图完整源代码和算法公式)_adrc算法_RXXW_Dor的博客-CSDN博客PLC的自抗扰控制(ADRC)算法_RXXW_Dor的博客-CSDN博客_adrc算法1、自抗扰控制算法,网上很多文章有所讲解,大家也可以关注韩京清…

6WINDGate-overview

6WINDGate Overview Author&#xff1a;Once Day Date&#xff1a;2023年4月29日 本文是对6WIND官网文档的整理和翻译&#xff0c;仅供学习和研究之用&#xff0c;原始文章可参考下面文档&#xff1a; 6WINDGate Documentation - 6WIND6WINDGate Modules — 6WINDGate Modul…

武忠祥老师每日一题||定积分基础训练(三)

常用的基本不等式&#xff1a; sin ⁡ x < x < t a n x , x ∈ ( 0 , π 2 ) \sin x<x<\ tan x,x\in(0,\frac{\pi}{2}) sinx<x< tanx,x∈(0,2π​) e x ≥ 1 x , x ∈ ( − ∞ , ∞ ) e^x\ge1x,x\in(-\infty,\infty) ex≥1x,x∈(−∞,∞) x 1 x ≤ ln …

Ubuntu20.04 交叉编译Paddle-OCR

第一步&#xff1a;交叉编译Paddle-Lite 参考链接&#xff1a;https://blog.csdn.net/sz76211822/article/details/130466597?spm1001.2014.3001.5501 第二步&#xff1a;交叉编译opencv4.x 参考链接&#xff1a;https://blog.csdn.net/sz76211822/article/details/13046168…

浅聊AIOT

引言 IoT是(Internet of Things)的简称&#xff0c;也就是人们常说的物联网&#xff1b;随着智能硬件的发展和推广&#xff0c;制造成本也随之下降&#xff0c;很多的厂家也慢慢地拥抱网络互联&#xff0c;逐步实现设备互联&#xff0c;也就进入了人们常说的万物互联时代。虽然…

linux网络统计指令:netstat

这里写自定义目录标题 一 netstat的作用以及安装命令1.1 作用1.2 安装命令 二 基本语法1.1 netstat -a1.2 netstat -e1.3 netstat -anp 三 查看指定端口的使用状况 一 netstat的作用以及安装命令 1.1 作用 主要用于显示IP和TCP、UDP与ICMP相关的统计数据&#xff0c;一般用于…

C++笔记——第十五篇 C++11来了 (上)

目录 1. C11简介 2. 列表初始化 2.1 C98中{}的初始化问题 2.2 内置类型的列表初始化 2.3 自定义类型的列表初始化 1. 标准库支持单个对象的列表初始化 2. 多个对象的列表初始化 3. 变量类型推导 3.1 为什么需要类型推导 3.2 decltype类型推导 3.2.1 为什么需要dec…

微服务全链路追踪选型:Zipkin、Pinpoint、SkyWalking、CAT

基于微服务架构&#xff0c;由于服务拆分粒度比较细&#xff0c;并且服务复用范围增大&#xff0c;不太可能再通过人工登记的方式进行接口调用情况的管理&#xff0c;因此对于每个请求的调用情况追踪将成为不可忽视的问题。追踪请求的调用情况&#xff0c;主要有几个作用&#…

分布式一致性Hash算法原理及实现【负载均衡】

文章目录 一致性Hash原理提高容错性和和扩展性一致性Hash实现思路代码 一致性Hash原理 简单来说&#xff0c;一致性Hash算法将整个哈希值空间组织成一个虚拟的圆环&#xff0c; 如假设某哈希函数 H 的值空间为 0 ~ 2^32-1&#xff08;即哈希值是一个32位无符号整形&#xff09;…

什么是POTDR?POTDR在光缆线路维护中有哪些应用

1 引言 OTDR&#xff08;Optical Time Domain Reflectometer&#xff0c;光时域反射仪&#xff09;是光缆线路工程及维护中的常用仪表&#xff0c;是利用光信号在光纤中传输时的瑞利散射和菲涅尔反射&#xff0c;通过反射曲线来了解光纤沿长度的损耗分布情况&#xff0c;可测量…

基于C#编程建立泛型Matrix数据类型及对应处理方法

一、简介 上一篇文档中描述了如何写一个Vector<T>类&#xff0c;本次在上一篇文档基础上&#xff0c;撰写本文&#xff0c;介绍如何书写一个泛型Matrix&#xff0c;可以应用于int、double、float等C#数值型的matrix。 本文所描述的Matrix<T>是一个泛型&#xff0c;…

一个人在家怎么赚钱?普通人如何通过网络实现在家就能赚钱

近年来&#xff0c;随着互联网的飞速发展&#xff0c;嗅觉敏锐的人只要使用互联网就可以快乐地赚钱。一般来说&#xff0c;网上赚钱的投资较少&#xff0c;有时有一台能上网的电脑或手机就够了&#xff0c;所以大家有时称其为“无成本或低成本网赚”。今天就分享一个人在家如何…

23种设计模式第一章:单例模式

这里写自定义目录标题 一 单例模式1 静态常量饿汉式2 静态代码块饿汉式3 线程不安全懒汉式4 线程安全懒汉式线程安全&#xff0c;同步方法线程安全&#xff0c;同步代码块 5 doubleCheck&#xff08;双重检查&#xff0c;推荐使用&#xff09;6 静态内部类7 枚举 一 单例模式 …

K8s 安全是云安全的未来

导语 到 2025 年&#xff0c;保护 Kubernetes (K8s) 将被认为是云安全最重要的方面。 在最成功的组织中&#xff0c;CTO 和 CISO 已经意识到 Kubernetes 安全的重要性。 但是&#xff0c;虽然 Kubernetes 已经占 CTO 云支出的很大一部分&#xff0c;但 CISO 仍然有所落后。 大…

基于web的课程重难点掌握情况分析系统

1&#xff0e;系统登录&#xff1a;系统登录是用户访问系统的路口&#xff0c;设计了系统登录界面&#xff0c;包括用户名、密码和验证码&#xff0c;然后对登录进来的用户判断身份信息&#xff0c;判断是管理员用户还是普通用户。 2&#xff0e;系统用户管理&#xff1a;不管是…

19.考虑柔性负荷的综合能源系统日前优化调度模型

说明书 MATLAB代码&#xff1a;考虑柔性负荷的综合能源系统日前优化调度模型 关键词&#xff1a;柔性负荷 需求响应 综合需求响应 日前优化调度 综合能源系统 参考文档&#xff1a;《考虑用户侧柔性负荷的社区综合能源系统日前优化调度》参考柔性负荷和基础模型部分&#xf…

脑电信号特征提取方法与应用

前言 脑电图(EEG)信号在理解与脑功能和脑相关疾病的电活动方面发挥着重要作用。典型的脑电信号分析流程如下&#xff1a;(1)数据采集&#xff1b;(2)数据预处理&#xff1b;(3)特征提取&#xff1b;(4)特征选择&#xff1b;(5)模型训练与分类&#xff1b;(6)性能评估。当信号分…

SpringClouid学习笔记(正在更新中...)

目录 SpringCloud1、微服务1.1、定义1.2、特性单体应用微服务应用 1.3、微服务架构演变&#xff08;RPC&#xff09;1.4、微服务解决方案 2、SpringCloud2.1、什么是SpringCloud官方定义DemoSpringCloud版本和SpringBoot版本选择 3、环境搭建环境说明构建方式开始构建 4、服务注…

全注解下的SpringIoc 续3-属性文件的使用

在Spring Boot中使用属性文件&#xff0c;可以采用默认的application.properties文件&#xff0c;也可以使用自定义的配置文件&#xff0c;下面让我们一起来看看这两个的使用。 使用默认的application.properties文件 这个配置文件是Spring Boot默认会加载的&#xff0c;所以…

自动抓取QQ好友列表?Windows UIA教你轻松实现

目录&#xff1a;导读 引言 选择Windows UIA框架进行自动化测试的原因 查找窗口 读取QQ软件的好友列表 结语 引言 每个使用QQ的人都有自己的好友列表&#xff0c;但是如果你想要查看所有好友信息&#xff0c;手动一个个点击会非常浪费时间。那么有没有什么快速获取好友列…