当前位置: 首页 > article >正文

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.kler.cn/news/17637.html

相关文章:

  • 【五一创作】网络协议与攻击模拟-01-wireshark使用-捕获过滤器
  • 【学习笔记】「JOISC 2022 Day1」错误拼写
  • git 撤销add/commit,以及更换源命令
  • Unity VFX -- (4)创建burst粒子效果
  • 图片损坏修复软件,分享好用靠谱的软件
  • 基于海洋捕食者算法的极限学习机(ELM)回归预测-附代码
  • Microelectronic学习章节总结(2)-- data path和control unit设计
  • Java时间类(三) -- Calendar()(日历类)
  • 如何搭建一个HTTP实验环境
  • nrf52840系列(一):环境配置
  • Android InputChannel事件发送接收系统分析
  • 1.1 n阶行列式子的定义
  • 2023年度国家自然科学基金项目申请初审结果公布~
  • kubernetes项目部署
  • Qt之滑动条和进度条(QSlider、QProgressBar)
  • 国产ChatGPT命名图鉴
  • 【Android入门到项目实战-- 9.2】—— 传感器实战使用教程(靠近黑屏和计步器)
  • 【C++】STL标准库之vector
  • macOS Monterey 12.6.5 (21G531) 正式版发布,ISO、IPSW、PKG 下载
  • Servlet原理
  • 由路由守卫引发的Angular DI inject思考
  • 【数据结构】二叉搜索树
  • TortoiseGit提示No supported authentication methods available异常
  • tab widget用法
  • 第一章(四):Django框架的模板(DTL):变量、标签、模板过滤器、模板继承、配置模板文件(staticfiles)
  • B树(B-tree、B-树)理论详解
  • SPSS如何进行方差分析之案例实训?
  • 蓝牙耳机哪款性价比高一些?2023年性价比最高的蓝牙耳机推荐
  • 一、spring Cloud Alibaba概述
  • No.046<软考>《(高项)备考大全》【专项2】《案例分析 - 计算题(中)》