axios概念介紹和基本使用
簡介
本文主要講解axios的概念和基本使用。
axios時目前最流行的ajax封裝庫之一,用于很方便地實(shí)現(xiàn)ajax請求的發(fā)送。
支持的功能:
- 從瀏覽器發(fā)出 XMLHttpRequests請求。
- 從 node.js 發(fā)出 http 請求。
- 支持 Promise API。
- 能攔截請求和響應(yīng)。
- 能轉(zhuǎn)換請求和響應(yīng)數(shù)據(jù)。
- 取消請求。
- 實(shí)現(xiàn)JSON數(shù)據(jù)的自動轉(zhuǎn)換。
- 客戶端支持防止 XSRF攻擊。
先借助json-server創(chuàng)建一個簡單的服務(wù),供ajax發(fā)送請求,json-server是一個簡單的可以接收restful的服務(wù)。
github地址:https://github.com/typicode/json-server
第一步:安裝:npm install -g json-server

第二步:創(chuàng)建一個名為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" }
}
第三步:啟動命令: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學(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ā)送請求的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學(xué)習(xí)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學(xué)習(xí)",
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>
請求的響應(yīng)結(jié)果結(jié)構(gòu)分析:

配置對象常用的配置項(xiàng):
{
// 路徑url
url: '/user',
// 請求方法,默認(rèn)get
method: 'get',
//基礎(chǔ)url,最終請求的url是 baseURL+url拼接,所以再全局設(shè)置默認(rèn),可以使得發(fā)送請求時的url變得簡潔
baseURL: 'https://some-domain.com/api/',
//設(shè)置請求頭
headers: {'X-Requested-With': 'XMLHttpRequest'},
//設(shè)置請求url的query參數(shù),可以使得url簡潔。
//比如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è)置請求體
data: {
firstName: 'Fred'
},
//設(shè)置請求的另外一種格式,不過這個是直接設(shè)置字符串的
data: 'Country=Brasil&City=Belo Horizonte',
//請求超時,單位毫秒,默認(rèn)0,不超時。
timeout: 1000,
//響應(yīng)數(shù)據(jù)類型,默認(rèn)json
responseType: 'json',
//響應(yīng)數(shù)據(jù)的編碼規(guī)則,默認(rèn)utf-8
responseEncoding: 'utf8',
//響應(yīng)體的最大長度
maxContentLength: 2000,
// 請求體的最大長度
maxBodyLength: 2000,
//設(shè)置響應(yīng)狀態(tài)碼為多少時是成功,調(diào)用resolve,否則調(diào)用reject失敗
//默認(rèn)是大于等于200,小于300
validateStatus: function (status) {
return status >= 200 && status < 300;
},
默認(rèn)配置
可以設(shè)置全局默認(rèn)配置,是為了避免多種重復(fù)配置在不同請求中重復(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,所以我們之后的請求只需要配置url不用像之前那樣的全路徑
axios.get("/posts/1")
.then(response=>{
console.log(response);
})
</script>
</body>
</html>

axios攔截器
實(shí)質(zhì)就是函數(shù)。
分為兩種類型:
- 請求攔截器:用于攔截請求,自定義做一個邏輯后再把請求發(fā)送,可以用于配置公用的邏輯,就不用每個請求都配一遍。
- 響應(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>
//這個是設(shè)置請求攔截器的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)
}
)
//這個是設(shè)置響應(yīng)攔截器的api,第一個成功回調(diào),第二個失敗回調(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("請求回調(diào)成功");
}).catch(function(error){
console.log("請求回調(diào)失敗");
})
</script>
</body>
</html>
效果:

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

效果:

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


可以看到請求攔截器類似棧,后進(jìn)先出,響應(yīng)攔截器類似隊(duì)列,先進(jìn)先出。
可以在請求攔截器中對config進(jìn)行調(diào)整,比如添加一個超時什么的,可以在響應(yīng)攔截器中對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>
//這個是設(shè)置請求攔截器的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){
//設(shè)置請求超時時間
config.timeout = 5000;
console.log("請求攔截器2調(diào)用成功");
return config;
},
function(error){
console.log("請求攔截器2調(diào)用失敗");
return Promise.reject(error)
}
)
//這個是設(shè)置響應(yīng)攔截器的api,第一個成功回調(diào),第二個失敗回調(diào)
axios.interceptors.response.use(
function(response){
console.log("響應(yīng)攔截器1調(diào)用成功");
console.log(response);
//返回到請求回調(diào)時,只要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("請求回調(diào)成功");
console.log(response);
}).catch(function(error){
console.log("請求回調(diào)失敗");
})
</script>
</body>
</html>
效果:

取消請求
取消請求就是發(fā)送了請求后,等待一段時間得不到回應(yīng),可以取消他。
<!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>
需要把服務(wù)器的響應(yīng)時間調(diào)到3秒,不然太快的話,演示不了取消請求。。
json-server --watch db.json -d 3000

總結(jié)
到此這篇關(guān)于axios概念介紹和基本使用的文章就介紹到這了,更多相關(guān)axios介紹和使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript的常見兼容問題及相關(guān)解決方法(chrome/IE/firefox)
本篇文章只要是對JavaScript的常見兼容問題及相關(guān)解決方法(chrome/IE/firefox)進(jìn)行了詳細(xì)的介紹,需要的朋友可以過來參考下,希望對大家有所幫助2013-12-12
JavaScript實(shí)現(xiàn)數(shù)組降維詳解
大家都知道將多維數(shù)組(尤其是二維數(shù)組)轉(zhuǎn)化為一維數(shù)組是業(yè)務(wù)開發(fā)中的常用邏輯,除了使用樸素的循環(huán)轉(zhuǎn)換以外,我們還可以利用Javascript的語言特性和數(shù)據(jù)結(jié)構(gòu)的思想實(shí)現(xiàn)更為簡潔優(yōu)雅的轉(zhuǎn)換。下面跟著小編一起來學(xué)習(xí)學(xué)習(xí)關(guān)于JavaScript如何實(shí)現(xiàn)數(shù)組降維吧。2017-01-01
JS運(yùn)動特效之完美運(yùn)動框架實(shí)例分析
這篇文章主要介紹了JS運(yùn)動特效之完美運(yùn)動框架,結(jié)合實(shí)例形式分析了javascript針對運(yùn)動中的元素屬性檢測與判斷相關(guān)操作技巧,需要的朋友可以參考下2018-01-01
用原生js統(tǒng)計(jì)文本行數(shù)的簡單示例
這篇文章我們來看看如何利用原生的JavaScript實(shí)現(xiàn)統(tǒng)計(jì)文本的行數(shù),代碼實(shí)現(xiàn)起來很簡單,有需要的可以參考借鑒。2016-08-08
javascript替換已有元素replaceChild()使用介紹
這篇文章主要介紹了javascript替換已有元素replaceChild()使用,需要的朋友可以參考下2014-04-04

