首页 > 其他分享 >axios 的请求方式

axios 的请求方式

时间:2022-11-30 13:44:57浏览次数:44  
标签:axios 请求 方式 get api 参数 net

1.绑定点击事件 get请求无参数

</head>

  <body>
    <h2>get请求+参数换地</h2>
    <button class="btn1">测试</button>
    <button class="btn2">测试有参数</button>
    <!-- <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> -->
    <script src="./lib/axios.js"></script>
    <script>
      // 1.绑定点击事件 get请求无参数
      const btn = document.querySelector(".btn1");
      btn.addEventListener("click", function () {
        // 请求方式1
        // axios({
        //   method: "get",
        //   url: "http://ajax-api.itheima.net/api/news",
        // })
        // 请求方2 axios.get("http://ajax-api.itheima.net/api/news")
        axios
          .get("http://ajax-api.itheima.net/api/news")
          .then(function (res) {
            console.log("返回接口成功时的结果");
          })
          .catch(function (err) {
            console.log("返回接口失败时的结果");
            console.log();
          });
      });
     </script>
  </body>
// 2.绑定点击事件 get请求有参数
</head>

  <body>
    <h2>get请求+参数换地</h2>
    <button class="btn1">测试</button>
    <button class="btn2">测试有参数</button>
    <!-- <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> -->
    <script src="./lib/axios.js"></script>
    <script>
   2.绑定点击事件 get请求有参数
      const btn2 = document.querySelector(".btn2");
      btn2.addEventListener("click", function () {
        // 请求携带参数的方法1URL地址后面直接拼接?属性名=属性值
        // axios.get("http://ajax-api.itheima.net/api/robot?spoken=你是谁")
//参数写在“”号里面 多个参数用&隔开
如axios.get("http://ajax-api.itheima.net/api/robot?属性名=属性值&属性名1=属性名2") // 请求携带参数的方法2
如axios .get("http://ajax-api.itheima.net/api/robot",
{params: { spoken(属性名): "你喜欢谁?(属性值)", },})
多个参数,号隔开写在params:{写这}里面 axios .get("http://ajax-api.itheima.net/api/robot", { params: { spoken: "你喜欢谁?", }, }) .then(function (res) { console.log(res); }) .catch(function (err) { console.log("出错"); }); }); </script> </body>

 

标签:axios,请求,方式,get,api,参数,net
From: https://www.cnblogs.com/JAG2671169285/p/16938141.html

相关文章