Axios 学习使用

1. 概念

是一个异步请求技术

基于XMLHttpRequest对象发起的请求都是异步请求

ajax可以用来发送异步请求,但过气了。vue全家桶都是采用的axios

2. 使用demo

下载地址 unpkg.com/axios/dist/...

get 方式请求

response.data 里面就是后端的数据

xml 复制代码
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script type="text/javascript">
      axios
        .get("http://localhost:6001/axios/findAll?username=dingyawu")
        .then(function (response) {
          console.log(response.data);
        })
        .catch(function (err) {
          console.log(err);
        });
    </script>

post请求

  1. axios在发送post请求传参如果是对象,axios会自动将对象转化为jsonstr,使用application/json 的请求头向后端传递参数
  2. axios的post请求传递参数的两种方式 "name=roy&age=23", 或者传递一个对象
xml 复制代码
    <script type="text/javascript">
     
      const params = {
        name: "roy",
        age: 23,
      };
      axios
        .post("http://localhost:6001/axios/save", params)
        .then(function (response) {
          console.log(response.data);
        })
        .catch(function (err) {
          console.log(err);
        });
    </script>

并发请求

针对并发请求用到axios.all(), 用axios.spread() 来汇总请求结果

xml 复制代码
    <script type="text/javascript">
      function findAll() {
        return axios.get(
          "http://localhost:6001/axios/findAll?username=dingyawu"
        );
      }
      const params = {
        name: "roy",
        age: 23,
      };

      function save() {
        return axios.post("http://localhost:6001/axios/save", params);
      }

      axios.all([findAll(), save()]).then(
        axios.spread(function (result1, result2) {
          console.log(result1.data);
          console.log(result2.data);
        })
      );
    </script>
相关推荐
_阿南_6 小时前
项目中新增给AI制定的代码规范
前端·程序员
名字还没想好☜7 小时前
React 实现暗黑模式切换:localStorage 持久化、SSR 首屏闪烁与跟随系统主题
前端·javascript·react.js·ecmascript·react·next.js
console.log('npc')8 小时前
Git 冲突与 AI 协助指南
前端·人工智能·git·大模型
爱学堂IT分享9 小时前
Cesium可视化系统实战课程-Cesium教程学习
前端
糖墨夕9 小时前
理解大语言模型:Agent 的“大脑”
前端·agent
Rain的Java大神之路9 小时前
JavaWeb开发如何解决跨域问题
java·前端·后端·nginx·web安全·面试·运维开发
cpolar技术支持10 小时前
浏览器也能跑本地 AI:用 Transformers.js + WebGPU 做一个最小推理 Demo,cpolar 给同事远程体验
前端·ai·cpolar·webgpu·transformers.js
计算机魔术师11 小时前
OpenAI 发布 GPT-6 Astra:多项基准刷新纪录, cybersecurity 能力达 Critical 阈值
前端
xy345311 小时前
Axure9.0中继器遮罩实现方法
前端·ui·html·axure·原型·产品设计
风骏时光牛马11 小时前
智能任务自动化协同AI工作流
前端