axios概念介紹和基本使用
簡介
本文主要講解axios的概念和基本使用。
axios時目前最流行的ajax封裝庫之一,用于很方便地實現(xiàn)ajax請求的發(fā)送。
支持的功能:
- 從瀏覽器發(fā)出 XMLHttpRequests請求。
- 從 node.js 發(fā)出 http 請求。
- 支持 Promise API。
- 能攔截請求和響應。
- 能轉(zhuǎn)換請求和響應數(shù)據(jù)。
- 取消請求。
- 實現(xiàn)JSON數(shù)據(jù)的自動轉(zhuǎn)換。
- 客戶端支持防止 XSRF攻擊。
先借助json-server創(chuàng)建一個簡單的服務,供ajax發(fā)送請求,json-server是一個簡單的可以接收restful的服務。
github地址:https://github.com/typicode/json-server
第一步:安裝:npm install -g json-server
第二步:創(chuàng)建一個名為db.json的文件,把網(wǎng)站的數(shù)據(jù)復制進去。
{ "posts": [ { "id": 1, "title": "json-server", "author": "typicode" } ], "comments": [ { "id": 1, "body": "some comment", "postId": 1 } ], "profile": { "name": "typicode" } }
第三步:啟動命令:json-server --watch db.json
訪問http://localhost:3000/posts 下面頁面為成功
使用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請求</button> <br><br> <button id="btn2">發(fā)送post請求</button><br><br> <button id="btn3">發(fā)送put請求</button><br><br> <button id="btn4">發(fā)送delete請求</button> <hr> <div>其他發(fā)送請求的api:</div><br><br> <button id="btn5">發(fā)送get請求1</button> <br><br> <button id="btn6">發(fā)送post請求1</button><br><br> <button id="btn7">發(fā)送put請求1</button><br><br> <button id="btn8">發(fā)送delete請求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學習", 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學習", 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ā)送請求的api document.getElementById("btn5").onclick = function(){ //發(fā)送get,使用get,第一個參數(shù)時url,第二個參數(shù)時config配置對象 axios.get("http://localhost:3000/posts/1") .then(response=>{ console.log(response); }) }; //發(fā)送post document.getElementById("btn6").onclick = function(){ //發(fā)送post請求,第一個參數(shù)時url,第二個參數(shù)時請求體,第三個參數(shù)時config配置對象 axios.post("http://localhost:3000/posts", {title:"axios學習2", author:"Yehaocong2"}) .then(response=>{ console.log(response); }) }; //發(fā)送put, document.getElementById("btn7").onclick = function(){ //發(fā)送put,接收三個參數(shù),url 請求體 、 config配置對象 axios.put("http://localhost:3000/posts/2",{title:"axios學習", author:"Liaoxiaoyan"}) .then(response=>{ console.log(response); }) }; document.getElementById("btn8").onclick = function(){ //發(fā)送delete請求,接收2個參數(shù), url config配置對象 axios.delete("http://localhost:3000/posts/3") .then(response=>{ console.log(response); }) }; //這個與axios({})基本相同 // axios.request({ // }) </script> </html>
請求的響應結(jié)果結(jié)構分析:
配置對象常用的配置項:
{ // 路徑url url: '/user', // 請求方法,默認get method: 'get', //基礎url,最終請求的url是 baseURL+url拼接,所以再全局設置默認,可以使得發(fā)送請求時的url變得簡潔 baseURL: 'https://some-domain.com/api/', //設置請求頭 headers: {'X-Requested-With': 'XMLHttpRequest'}, //設置請求url的query參數(shù),可以使得url簡潔。 //比如url是https://some-domain.com/api/user 然后params如下設置,那么最終的url是: //https://some-domain.com/api/user?ID=12345&name=Jack params: { ID: 12345, name:"Jack" }, //設置請求體 data: { firstName: 'Fred' }, //設置請求的另外一種格式,不過這個是直接設置字符串的 data: 'Country=Brasil&City=Belo Horizonte', //請求超時,單位毫秒,默認0,不超時。 timeout: 1000, //響應數(shù)據(jù)類型,默認json responseType: 'json', //響應數(shù)據(jù)的編碼規(guī)則,默認utf-8 responseEncoding: 'utf8', //響應體的最大長度 maxContentLength: 2000, // 請求體的最大長度 maxBodyLength: 2000, //設置響應狀態(tài)碼為多少時是成功,調(diào)用resolve,否則調(diào)用reject失敗 //默認是大于等于200,小于300 validateStatus: function (status) { return status >= 200 && status < 300; },
默認配置
可以設置全局默認配置,是為了避免多種重復配置在不同請求中重復,比如baseURL、timeout等,這里設置baseURL。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>默認配置</title> </head> <body> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> axios.defaults.baseURL="http://localhost:3000"; //因為上面配置了baseURL,所以我們之后的請求只需要配置url不用像之前那樣的全路徑 axios.get("/posts/1") .then(response=>{ console.log(response); }) </script> </body> </html>
axios攔截器
實質(zhì)就是函數(shù)。
分為兩種類型:
- 請求攔截器:用于攔截請求,自定義做一個邏輯后再把請求發(fā)送,可以用于配置公用的邏輯,就不用每個請求都配一遍。
- 響應攔截器:用于攔截響應,做一些處理后再出發(fā)響應回調(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> //這個是設置請求攔截器的api,傳入兩個回調(diào),第一個成功回調(diào),第二個失敗回調(diào)。 axios.interceptors.request.use( function(config){ console.log("請求攔截器1調(diào)用成功"); return config; }, function(error){ console.log("請求攔截器1調(diào)用失敗"); return Promise.reject(error) } ) //這個是設置響應攔截器的api,第一個成功回調(diào),第二個失敗回調(diào) axios.interceptors.response.use( function(response){ console.log("響應攔截器1調(diào)用成功"); return response; }, function(error){ console.log("響應攔截器1調(diào)用失敗"); return Promise.reject(error); } ) axios.get("http://localhost:3000/posts/1") .then(function(response){ // console.log("請求回調(diào)成功"); }).catch(function(error){ console.log("請求回調(diào)失敗"); }) </script> </body> </html>
效果:
要理解這些個攔截器需要由一定的es6 Promise基礎,出現(xiàn)上面效果的原因是,發(fā)送請求前,請求被請求攔截器攔截了,并且請求攔截器返回了一個非Promise實例的對象config,所以下一個攔截器是調(diào)用成功回調(diào)的,所以就打印響應攔截器成功,然后響應攔截器成功的回調(diào)返回的是非Promise實例的對象response,所以最終的請求回調(diào)是調(diào)用成功的回調(diào),所以返回請求調(diào)用成功。
嘗試以下再請求攔截器的成功回調(diào)中,返回reject狀態(tài)的Promise。
效果:
出現(xiàn)上面效果的原因是,請求攔截器的成功回調(diào)中最后返回了reject狀態(tài)的Promise實例對象,被判斷為失敗,到了回調(diào)鏈的下一回調(diào),也就是響應攔截器的回調(diào)時,調(diào)用的時失敗的回調(diào),失敗的回調(diào)中又返回了reject狀態(tài)的Promise實例對象,所以到了真正請求的回調(diào)頁調(diào)用了失敗回調(diào)。
上面的效果與Promise如出一轍。
多個攔截器的效果:加了一個請求攔截器一個響應攔截器:
可以看到請求攔截器類似棧,后進先出,響應攔截器類似隊列,先進先出。
可以在請求攔截器中對config進行調(diào)整,比如添加一個超時什么的,可以在響應攔截器中對response返回值進行調(diào)整,比如我返回到回調(diào)函數(shù)中只想要響應體部分。
<!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> //這個是設置請求攔截器的api,傳入兩個回調(diào),第一個成功回調(diào),第二個失敗回調(diào)。 axios.interceptors.request.use( function(config){ console.log("請求攔截器1調(diào)用成功"); return config; }, function(error){ console.log("請求攔截器1調(diào)用失敗"); return Promise.reject(error) } ) axios.interceptors.request.use( function(config){ //設置請求超時時間 config.timeout = 5000; console.log("請求攔截器2調(diào)用成功"); return config; }, function(error){ console.log("請求攔截器2調(diào)用失敗"); return Promise.reject(error) } ) //這個是設置響應攔截器的api,第一個成功回調(diào),第二個失敗回調(diào) axios.interceptors.response.use( function(response){ console.log("響應攔截器1調(diào)用成功"); console.log(response); //返回到請求回調(diào)時,只要data數(shù)據(jù) return response.data; }, function(error){ console.log("響應攔截器1調(diào)用失敗"); return Promise.reject(error); } ) axios.interceptors.response.use( function(response){ console.log("響應攔截器2調(diào)用成功"); return response; }, function(error){ console.log("響應攔截器2調(diào)用失敗"); return Promise.reject(error); } ) axios.get("http://localhost:3000/posts/1") .then(function(response){ // console.log("請求回調(diào)成功"); console.log(response); }).catch(function(error){ console.log("請求回調(diào)失敗"); }) </script> </body> </html>
效果:
取消請求
取消請求就是發(fā)送了請求后,等待一段時間得不到回應,可以取消他。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>axios取消請求</title> </head> <body> <button id="btn1">發(fā)送請求</button> <button id="btn2">取消請求</button> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> //第一步:定義一個全局的cancel變量,初始值是null let cancel = null; document.getElementById("btn1").onclick = function(){ axios.get("http://localhost:3000/posts/1", { //第二步:在請求的配置對象中,配置cancelToken屬性值,并把函數(shù)的c參數(shù)賦值給全局變量cancel cancelToken:new axios.CancelToken(function(c){ cancel = c; }) }) .then(function(response){ // console.log(response); }).catch(function(error){ console.log("請求回調(diào)失敗"); }) } document.getElementById("btn2").onclick = function(){ //第三步:調(diào)用cancel函數(shù)就是取消請求接收 cancel(); } </script> </body> </html>
需要把服務器的響應時間調(diào)到3秒,不然太快的話,演示不了取消請求。。
json-server --watch db.json -d 3000
總結(jié)
到此這篇關于axios概念介紹和基本使用的文章就介紹到這了,更多相關axios介紹和使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決一個微信號同時支持多個環(huán)境網(wǎng)頁授權問題
由于微信限制一個服務號只能配置一個網(wǎng)頁授權域名, 又不可能給每個環(huán)境單獨配一個服務號,這樣不僅需要成本而且很浪費資源,下面小編給大家?guī)砹私鉀Q一個微信號同時支持多個環(huán)境網(wǎng)頁授權問題,感興趣的朋友一起看看吧2019-08-08JavaScript ES6中const、let與var的對比詳解
這篇文章主要給大家介紹了在JavaScript中const、let與var對比的相關資料,文中通過示例代碼介紹的非常詳細,對大家具有一定的參考學習價值,需要的朋友們下面跟著小編來一起看看吧。2017-06-06Canvas實現(xiàn)數(shù)字雨和放大鏡效果的代碼示例
這篇文章主要介紹了如何Canvas實現(xiàn)數(shù)字雨和放大鏡效果,文中有完整的代碼示例,文章通過代碼介紹的非常清楚,感興趣的小伙伴跟著小編一起來看看吧2023-07-07js 將input框中的輸入自動轉(zhuǎn)化成半角大寫(稅號輸入框)
本文主要介紹了稅號輸入框:將input框中的輸入自動轉(zhuǎn)化成半角大寫的方法,具有很好的參考價值,下面跟著小編一起來看下吧2017-02-02JavaScript創(chuàng)建防篡改對象的方法分析
這篇文章主要介紹了JavaScript創(chuàng)建防篡改對象的方法,結(jié)合具體實例形式分析了javascript基于不可擴展對象、密封的對象和凍結(jié)的對象實現(xiàn)防篡改對象的相關操作技巧,需要的朋友可以參考下2018-12-12