一、什麼是 axios ?

axios是基於 Promise 的 ajax 封裝庫,也是前端目前最流行的 ajax 請求庫。簡單地說傳送 get、post 請求,是一個輕量級的庫,使用時可直接引入。

二、axios 的特點

  1. 非同步的 ajax 請求庫。
  2. 在瀏覽器端和 node 端都可以使用。
  3. 支援 Promise API。
  4. 支援請求和響應攔截。
  5. 響應資料自動轉換 JSON 資料。
  6. 支援請求取消。
  7. 可以批量傳送多個請求。
  8. 客戶端支援安全保護,免受 XSRF 攻擊。

三、axios API

3.1、安裝

/* npm 安裝 */
npm install axios --save /* bower 安裝 */
bower install axios /* 使用 yarn */
yarn add axios /* cdn 引入 */
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

注:如果簡單靜態頁面使用,建議cdn方式引入。

3.2、axios API

向 axios 傳輸相關配置引數,建立請求。如:axios(config)

/* 如傳送一個post請求的配置引數如下 */
axios({
method: 'post', //請求方法
url: '/user/12345', //訪問介面
data: { //傳輸資料
firstName: 'Fred',
lastName: 'Flintstone'
}
});
/* 如傳送一個get請求的配置引數如下 */
axios({
method: 'get',
url: 'http://localhost:80/one',//請求介面
responseType: 'stream'//響應形式
})
.then(function (response) {
response.data.pipe(fs.createWriteStream('save.jpg')) //儲存圖片
});

3.3、axios 請求方法

上邊axios API 每發起一個請求,都需要設定它的請求方法和響應頭超時等資訊,使用起來比較繁瑣,為了方便,axios 為所有支援的請求方法提供了別名,可直接指定方式發起請求,其他引數可通過全域性設定。如:

axios('/user/id=1');

上述 axios 直接傳送請求,不設定請求方式時,預設使用 get 請求,與 ajax 和 fetch 相同。所以傳送的是一個get請求,也可以使用 get 方法傳送,如下例項:

axios.get(
'1.txt' ,
{
params:{id:'1'}
}
).then(res=>{
console.log(res);
})
.catch(err=>{
console.log(err);
})

可簡寫成 axios(url,config)。

具體的其他方法分別為:

axios.request(config)
axios.get( url , config)
axios.delete( url , config)
axios.head( url , config)
axios.options( url , config)
axios.post( url [,data [, config ]])
axios.put( url [,data [, config ]])
axios.patch( url [,data [, config ]])

3.4、批量傳送請求

網路請求中往往會有多個網路請求併發執行,有時需要統一處理它們返回結果,所以axios有併發處理。axios.all()可以並行傳送多個網路請求,等待請求都返回之後,繼續處理。

使用語法:

/* 第一種處理方式 */
axios.all([
axios.get(URL1),
axios.get(URL2),
]).then(res=>{
console.log(res) //返回的res是一個數組,res[0]是第一個請求資料 res[1]是第二個請求資料
}) /* 第二種處理方式 */
axios.all([
axios.get(URL1),
axios.get(URL2),
]).then(
axios.spread((res1,res2)=>{
res1 //是第一個請求返回資料
res2 //是第二個請求返回資料
})
)

使用 axios.spread 能夠自動分割請求返回資料。

1.5、全域性預設配置

全域性預設配置主要作用於每個請求。既節省敲程式碼的時間,想修改的時候,只需修改一個就可以全部修改掉。

常見的全域性預設配置有:

axios.defaults.baseURL = "http://localhost:8080/" //配置域名
axios.defaults.timeout = 6000; //單位是毫秒,設定超時時間 /* 頭設定 */
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

3.6、axios 例項

// 例項化的時候配置預設引數
const instance = axios.create({
baseURL: 'https://api.example.com'
}); // Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN

之所以使用 axios 例項化,是因為全域性例項化 http 請求有全域性的響應攔截,當我們某些介面無法返回狀態碼時,我們將無法得到 response,此時我們需要在當前 api 中重新例項化一個 axios,設定新的響應攔截碼。

3.7、攔截器

攔截器分為兩個,有請求攔截和響應攔截,可以統一處理某些業務。

  • 請求攔截器:
/*
請求攔截器
統一在傳送請求之前新增token
*/
axios.interceptors.request.use(config=>{
config.headers.token = sessionStorage.getItem("token") //新增toke
return config
},err=>{
console.log(err)//請求錯誤
})
  • 響應攔截器
axios.interceptors.response.use(response=>{
return response
},err=>{
console.log(err)//響應錯誤
})

3.8、響應內容

基本使用中,第一個例項請求成功,列印結果 console.log(res) 。返回結果如下:

{
data:{},
status:200,
//從伺服器返回的http狀態文字
statusText:'OK',
//響應頭資訊
headers: {},
//config是在請求的時候的一些配置資訊
config: {}
}

四、axios 常見應用

axios既可以在瀏覽器端使用,也可以在node.js中使用。在瀏覽器端傳送的是XMLHttpRequest,在 node.js 傳送的是 http 。像VUE、React、Node等專案都可以使用axios。