欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

axios概念介紹和基本使用

 更新時(shí)間:2022年06月06日 14:43:27   作者:我會(huì)努力變強(qiáng)的  
axios是一個(gè)基于Promise用于瀏覽器和nodejs的HTTP客戶端,下面這篇文章主要給大家介紹了關(guān)于axios概念介紹和基本使用的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下

簡(jiǎn)介

本文主要講解axios的概念和基本使用。

axios時(shí)目前最流行的ajax封裝庫(kù)之一,用于很方便地實(shí)現(xiàn)ajax請(qǐng)求的發(fā)送。

支持的功能:

  • 從瀏覽器發(fā)出 XMLHttpRequests請(qǐng)求。
  • 從 node.js 發(fā)出 http 請(qǐng)求。
  • 支持 Promise API。
  • 能攔截請(qǐng)求和響應(yīng)。
  • 能轉(zhuǎn)換請(qǐng)求和響應(yīng)數(shù)據(jù)。
  • 取消請(qǐng)求。
  • 實(shí)現(xiàn)JSON數(shù)據(jù)的自動(dòng)轉(zhuǎn)換。
  • 客戶端支持防止 XSRF攻擊。

先借助json-server創(chuàng)建一個(gè)簡(jiǎn)單的服務(wù),供ajax發(fā)送請(qǐng)求,json-server是一個(gè)簡(jiǎn)單的可以接收restful的服務(wù)。

github地址:https://github.com/typicode/json-server

第一步:安裝:npm install -g json-server

第二步:創(chuàng)建一個(gè)名為db.json的文件,把網(wǎng)站的數(shù)據(jù)復(fù)制進(jìn)去。

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}

第三步:?jiǎn)?dòng)命令:json-server --watch db.json

訪問http://localhost:3000/posts 下面頁(yè)面為成功

使用axios

GitHub地址:https://github.com/axios/axios

為了方便,我們直接使用第四種。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>axios基本使用</title>
</head>
<body>
    <button id="btn1">發(fā)送get請(qǐng)求</button> <br><br>
    <button id="btn2">發(fā)送post請(qǐng)求</button><br><br>
    <button id="btn3">發(fā)送put請(qǐng)求</button><br><br>
    <button id="btn4">發(fā)送delete請(qǐng)求</button>

    <hr>

    <div>其他發(fā)送請(qǐng)求的api:</div><br><br>
    <button id="btn5">發(fā)送get請(qǐng)求1</button> <br><br>
    <button id="btn6">發(fā)送post請(qǐng)求1</button><br><br>
    <button id="btn7">發(fā)送put請(qǐng)求1</button><br><br>
    <button id="btn8">發(fā)送delete請(qǐng)求1</button>
</body>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
    //發(fā)送get
    document.getElementById("btn1").onclick = function(){
       axios({
        method:"GET",
        url:"http://localhost:3000/posts/1"
       }).then(response=>{
           console.log(response);
       })
    };

    //發(fā)送post
    document.getElementById("btn2").onclick = function(){
       axios({
        method:"POST",
        url:"http://localhost:3000/posts",
        data:{
            title:"axios學(xué)習(xí)",
            author:"Yehaocong"
        }
       }).then(response=>{
           console.log(response);
       })
    };
    //發(fā)送put
    document.getElementById("btn3").onclick = function(){
       axios({
        method:"PUT",
        url:"http://localhost:3000/posts/2",
        data:{
            title:"axios學(xué)習(xí)",
            author:"Liaoxiaoyan"
        }
       }).then(response=>{
           console.log(response);
       })
    };
    document.getElementById("btn4").onclick = function(){
       axios({
        method:"DELETE",
        url:"http://localhost:3000/posts/2",
       }).then(response=>{
           console.log(response);
       })
    };



    //其他發(fā)送請(qǐng)求的api

    
    document.getElementById("btn5").onclick = function(){
        //發(fā)送get,使用get,第一個(gè)參數(shù)時(shí)url,第二個(gè)參數(shù)時(shí)config配置對(duì)象
       axios.get("http://localhost:3000/posts/1")
       .then(response=>{
           console.log(response);
       })
    };

    //發(fā)送post
    document.getElementById("btn6").onclick = function(){
        //發(fā)送post請(qǐng)求,第一個(gè)參數(shù)時(shí)url,第二個(gè)參數(shù)時(shí)請(qǐng)求體,第三個(gè)參數(shù)時(shí)config配置對(duì)象
        axios.post("http://localhost:3000/posts",
        {title:"axios學(xué)習(xí)2",
            author:"Yehaocong2"})
            .then(response=>{
           console.log(response);
       })
    };
    //發(fā)送put,
    document.getElementById("btn7").onclick = function(){
        //發(fā)送put,接收三個(gè)參數(shù),url  請(qǐng)求體 、 config配置對(duì)象
       axios.put("http://localhost:3000/posts/2",{title:"axios學(xué)習(xí)",
            author:"Liaoxiaoyan"})
       .then(response=>{
           console.log(response);
       })
    };
    document.getElementById("btn8").onclick = function(){
        //發(fā)送delete請(qǐng)求,接收2個(gè)參數(shù), url config配置對(duì)象
        axios.delete("http://localhost:3000/posts/3")
       .then(response=>{
           console.log(response);
       })
    };

    //這個(gè)與axios({})基本相同
    // axios.request({

    // })
</script>
</html>

請(qǐng)求的響應(yīng)結(jié)果結(jié)構(gòu)分析:

配置對(duì)象常用的配置項(xiàng):

{
  // 路徑url
  url: '/user',

  // 請(qǐng)求方法,默認(rèn)get
  method: 'get', 

  //基礎(chǔ)url,最終請(qǐng)求的url是 baseURL+url拼接,所以再全局設(shè)置默認(rèn),可以使得發(fā)送請(qǐng)求時(shí)的url變得簡(jiǎn)潔
  baseURL: 'https://some-domain.com/api/',

  //設(shè)置請(qǐng)求頭
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  //設(shè)置請(qǐng)求url的query參數(shù),可以使得url簡(jiǎn)潔。
  //比如url是https://some-domain.com/api/user  然后params如下設(shè)置,那么最終的url是:
  //https://some-domain.com/api/user?ID=12345&name=Jack
  params: {
    ID: 12345,
    name:"Jack"
  },


 //設(shè)置請(qǐng)求體
  data: {
    firstName: 'Fred'
  },
  
  //設(shè)置請(qǐng)求的另外一種格式,不過這個(gè)是直接設(shè)置字符串的
  data: 'Country=Brasil&City=Belo Horizonte',

 //請(qǐng)求超時(shí),單位毫秒,默認(rèn)0,不超時(shí)。
  timeout: 1000,

  //響應(yīng)數(shù)據(jù)類型,默認(rèn)json
  responseType: 'json', 

  //響應(yīng)數(shù)據(jù)的編碼規(guī)則,默認(rèn)utf-8
  responseEncoding: 'utf8',


	//響應(yīng)體的最大長(zhǎng)度 
  maxContentLength: 2000,

  // 請(qǐng)求體的最大長(zhǎng)度
  maxBodyLength: 2000,

  //設(shè)置響應(yīng)狀態(tài)碼為多少時(shí)是成功,調(diào)用resolve,否則調(diào)用reject失敗
  //默認(rèn)是大于等于200,小于300
  validateStatus: function (status) {
    return status >= 200 && status < 300; 
  },

默認(rèn)配置

可以設(shè)置全局默認(rèn)配置,是為了避免多種重復(fù)配置在不同請(qǐng)求中重復(fù),比如baseURL、timeout等,這里設(shè)置baseURL。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>默認(rèn)配置</title>
</head>
<body>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
        axios.defaults.baseURL="http://localhost:3000";

        //因?yàn)樯厦媾渲昧薭aseURL,所以我們之后的請(qǐng)求只需要配置url不用像之前那樣的全路徑
        axios.get("/posts/1")
       .then(response=>{
           console.log(response);
       })

    
    </script>
</body>
</html>

axios攔截器

實(shí)質(zhì)就是函數(shù)。

分為兩種類型:

  • 請(qǐng)求攔截器:用于攔截請(qǐng)求,自定義做一個(gè)邏輯后再把請(qǐng)求發(fā)送,可以用于配置公用的邏輯,就不用每個(gè)請(qǐng)求都配一遍。
  • 響應(yīng)攔截器:用于攔截響應(yīng),做一些處理后再出發(fā)響應(yīng)回調(diào)。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>axios攔截器</title>
</head>
<body>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
        //這個(gè)是設(shè)置請(qǐng)求攔截器的api,傳入兩個(gè)回調(diào),第一個(gè)成功回調(diào),第二個(gè)失敗回調(diào)。
        axios.interceptors.request.use(
            function(config){
                console.log("請(qǐng)求攔截器1調(diào)用成功");
                return config;
            },
            function(error){
                console.log("請(qǐng)求攔截器1調(diào)用失敗");
                return Promise.reject(error)
            }
        )

        //這個(gè)是設(shè)置響應(yīng)攔截器的api,第一個(gè)成功回調(diào),第二個(gè)失敗回調(diào)
        axios.interceptors.response.use(
            function(response){
                console.log("響應(yīng)攔截器1調(diào)用成功");
                return response;
            },
            function(error){
                console.log("響應(yīng)攔截器1調(diào)用失敗");
                return Promise.reject(error);
            }
        )

        axios.get("http://localhost:3000/posts/1")
        .then(function(response){
            //
            console.log("請(qǐng)求回調(diào)成功");
        }).catch(function(error){
            console.log("請(qǐng)求回調(diào)失敗");
        })
    </script>
</body>
</html>

效果:

要理解這些個(gè)攔截器需要由一定的es6 Promise基礎(chǔ),出現(xiàn)上面效果的原因是,發(fā)送請(qǐng)求前,請(qǐng)求被請(qǐng)求攔截器攔截了,并且請(qǐng)求攔截器返回了一個(gè)非Promise實(shí)例的對(duì)象config,所以下一個(gè)攔截器是調(diào)用成功回調(diào)的,所以就打印響應(yīng)攔截器成功,然后響應(yīng)攔截器成功的回調(diào)返回的是非Promise實(shí)例的對(duì)象response,所以最終的請(qǐng)求回調(diào)是調(diào)用成功的回調(diào),所以返回請(qǐng)求調(diào)用成功。

嘗試以下再請(qǐng)求攔截器的成功回調(diào)中,返回reject狀態(tài)的Promise。

效果:

出現(xiàn)上面效果的原因是,請(qǐng)求攔截器的成功回調(diào)中最后返回了reject狀態(tài)的Promise實(shí)例對(duì)象,被判斷為失敗,到了回調(diào)鏈的下一回調(diào),也就是響應(yīng)攔截器的回調(diào)時(shí),調(diào)用的時(shí)失敗的回調(diào),失敗的回調(diào)中又返回了reject狀態(tài)的Promise實(shí)例對(duì)象,所以到了真正請(qǐng)求的回調(diào)頁(yè)調(diào)用了失敗回調(diào)。

上面的效果與Promise如出一轍。

多個(gè)攔截器的效果:加了一個(gè)請(qǐng)求攔截器一個(gè)響應(yīng)攔截器:

可以看到請(qǐng)求攔截器類似棧,后進(jìn)先出,響應(yīng)攔截器類似隊(duì)列,先進(jìn)先出。

可以在請(qǐng)求攔截器中對(duì)config進(jìn)行調(diào)整,比如添加一個(gè)超時(shí)什么的,可以在響應(yīng)攔截器中對(duì)response返回值進(jìn)行調(diào)整,比如我返回到回調(diào)函數(shù)中只想要響應(yīng)體部分。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>axios攔截器</title>
</head>
<body>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
        //這個(gè)是設(shè)置請(qǐng)求攔截器的api,傳入兩個(gè)回調(diào),第一個(gè)成功回調(diào),第二個(gè)失敗回調(diào)。
        axios.interceptors.request.use(
            function(config){
                console.log("請(qǐng)求攔截器1調(diào)用成功");
                return config;
            },
            function(error){
                console.log("請(qǐng)求攔截器1調(diào)用失敗");
                return Promise.reject(error)
            }
        )

        axios.interceptors.request.use(
            function(config){
                //設(shè)置請(qǐng)求超時(shí)時(shí)間
                config.timeout = 5000;
                console.log("請(qǐng)求攔截器2調(diào)用成功");
                return config;
            },
            function(error){
                console.log("請(qǐng)求攔截器2調(diào)用失敗");
                return Promise.reject(error)
            }
        )

        //這個(gè)是設(shè)置響應(yīng)攔截器的api,第一個(gè)成功回調(diào),第二個(gè)失敗回調(diào)
        axios.interceptors.response.use(
            function(response){
                console.log("響應(yīng)攔截器1調(diào)用成功");
                 console.log(response);
                //返回到請(qǐng)求回調(diào)時(shí),只要data數(shù)據(jù)
                return response.data;
            },
            function(error){
                console.log("響應(yīng)攔截器1調(diào)用失敗");
                return Promise.reject(error);
            }
        )
        axios.interceptors.response.use(
            function(response){
                console.log("響應(yīng)攔截器2調(diào)用成功");
                return response;
            },
            function(error){
                console.log("響應(yīng)攔截器2調(diào)用失敗");
                return Promise.reject(error);
            }
        )

        axios.get("http://localhost:3000/posts/1")
        .then(function(response){
            //
            console.log("請(qǐng)求回調(diào)成功");
            console.log(response);
        }).catch(function(error){
            console.log("請(qǐng)求回調(diào)失敗");
        })
    </script>
</body>
</html>

效果:

取消請(qǐng)求

取消請(qǐng)求就是發(fā)送了請(qǐng)求后,等待一段時(shí)間得不到回應(yīng),可以取消他。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>axios取消請(qǐng)求</title>
</head>
<body>
    <button id="btn1">發(fā)送請(qǐng)求</button>
    <button id="btn2">取消請(qǐng)求</button>



    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
        //第一步:定義一個(gè)全局的cancel變量,初始值是null
        let cancel = null;
        document.getElementById("btn1").onclick = function(){
            axios.get("http://localhost:3000/posts/1",
            {
                //第二步:在請(qǐng)求的配置對(duì)象中,配置cancelToken屬性值,并把函數(shù)的c參數(shù)賦值給全局變量cancel
                cancelToken:new axios.CancelToken(function(c){
                    cancel = c;
                })
            })
        .then(function(response){
            //
            console.log(response);
        }).catch(function(error){
            console.log("請(qǐng)求回調(diào)失敗");
        })
        }

        document.getElementById("btn2").onclick = function(){
            //第三步:調(diào)用cancel函數(shù)就是取消請(qǐng)求接收
            cancel();
        }
    </script>
</body>
</html>

需要把服務(wù)器的響應(yīng)時(shí)間調(diào)到3秒,不然太快的話,演示不了取消請(qǐng)求。。

json-server  --watch  db.json -d 3000

總結(jié) 

到此這篇關(guān)于axios概念介紹和基本使用的文章就介紹到這了,更多相關(guān)axios介紹和使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論