axios作爲Vue官方推薦的vue-rourse替代品,其自身優點很多,經常用於網絡請求。
現在對其進行說明。
之所以不用jquery的ajax進行請求,是因爲jquery體積過大。
我們首先得明確的是,在使用Vue進行項目開發過程中,如果使用的是jquery的ajax,需要引入jquery,但是jquery本身的體積就有代碼1w行左右,顯然爲了使用ajax就另外引入這麼多代碼是不合理的。所以使用vue官方推薦的axios是不二之選。
axios的常用API請求有以下這些:
axios(config)
axios.request(config)
axios.get(url,config)
axios.post(url[,data[,config]])
axios.delete(url[,config])
get請求演示:
import axios from "axios";
export default {
name:"app",
created() {
// 沒有請求參數
axios.get("http://......")
.then(res => {
// res的處理代碼
}).catch(err => {
// err的處理代碼
})
// 有請求參數
axios.get("http://......",{params:{type:"sell",page:1}})
.then(res => {
// res的處理代碼
}).catch(err => {
// err的處理代碼
})
}
}
有時候我們需要同時發送兩個請求,這時可以使用all 方法,將多個請求放入all方法的數組裏,然後使用spread方法處理返回結果。
並非請求處理,以get請求爲例:
import axios from "axios";
export default {
name:"app",
created() {
axios.all([axios.get("http://......"),
axios.get("http://......",{params:{type:"sell",page:1}})])
.then(axios.spread((res1,res2) => {
// res1處理代碼
// res2處理代碼
}))
}
}
說明:all方法的出現使寫多個請求時的代碼更加簡潔。
全局配置
有時候一些公共的配置可以利用axios的全局配置來處理。
全局配置舉例:
created() {
// 相同的URL部分進行配置
axios.default.baseURL = "http://123.2.3.5:8080";
// 請求超時
axios.default.timeout = 5000;
// 自定義請求頭
axios.default.headers: {
"Content-type":"applications/x-www-form-urlencoded"
}
// 發送請求
axios.get("http://......").then(res => {
// res的處理代碼
})
}
說明:還有其他配置項:
請求類型
method:"get"
URL查詢對象
params:{id:123}
跨域是否帶token
withCredentials:false
自定義請求處理
adapter:(resolve,reject,config) => {}
響應的數據格式:json/text/blob/document/stream/arraybuffer
responseType:"json"
創建實例
到目前爲止,我們使用的是默認的axios實例對象,配置這個默認的實例時很多配置項就都固定下來了,但是很多時候這些配置會不一樣,比如timeout或baseURL等等。
這時候可以自己創建axios實例。
const axiosInstance = axios.create({
baseURL:"http://123.2.4.5:8080",
timeout:5000,
headers: {
"Content-type":"application/x-www-urlencoded"
}
})
攔截器
axios攔截器用於在發送請求前和請求響應後,進行響應的處理。
所以分爲request請求攔截器和response響應攔截器兩種。
request請求攔截器:發送請求前統一處理,如:設置請求頭headers、應用的版本號、終端類型等。
response響應攔截器:有時候我們要根據響應的狀態碼來進行下一步操作,例如:由於當前的token過期,接口返回401未授權,那我們就要進行重新登錄的操作。
example:發送請求之前判斷是否存在token,除了登錄頁,其他頁面請求頭headers都添加token:
// http request 請求攔截器
axios.interceptors.request.use(config => {
// 在發送請求之前做些什麼
let pathname = location.pathname;
if(localStorage.getItem('token')){
if(pathname != '/' && pathname != '/login'){
config.headers.common['token'] = localStorage.getItem('token');
}
}
return config;
}, error => {
// 對請求錯誤做些什麼
return Promise.reject(error);
});
example:若返回401,頁面跳轉到登錄頁面:
// http response 響應攔截器
axios.interceptors.response.use(response => {
return response;
},error => {
if (error.response) {
switch (error.response.status) {
// 返回401,清除token信息並跳轉到登錄頁面
case 401:
localStorage.removeItem('token');
router.replace({
path: '/login'
//登錄成功後跳入瀏覽的當前頁面
// query: {redirect: router.currentRoute.fullPath}
})
}
// 返回接口返回的錯誤信息
return Promise.reject(error.response.data);
}
});
說明:請查閱博客:https://blog.csdn.net/weixin_39378691/article/details/83750056
axios封裝
經過上面對axios的瞭解,可以對axios進行一個簡單的封裝。
instance.js:
import axios from "axios";
export const instance = axios.create({
baseURL:"https://123.2.3.5:8080";
timeout:5000;
headers:{
"Content-type":"application/x-www-urlencoded"
//其他類型:'Content-Type': 'application/json;charset=UTF-8'
}
});
instance.interceptor.request.use(config => {
// 處理邏輯代碼
// 返回config
return config;
}
instance.interceptor.response.use(res => {
// 處理邏輯代碼
// 返回res
return res.data;
},err => {
// 處理邏輯代碼
// 返回Promise對象
return Promise.reject(err);
})
再封裝一層,request.js:
import instance from "./instance.js"
export function getHomeInfo() {
return instance({
url:"...",
method:"get"
})
}
export function getProfileInfo(personId) {
return instance({
url:"...",
params:{personId:personId}
})
}
export function getAllShopInfo(data) {
return instance({
url:"...",
data:JSON.stringify(data)
})
}
這樣一來,組件裏調用request.js封裝的請求就很方便了,而且組件對axios插件的依賴降到最低,這也是我們希望的:
<template>
//......
</template>
<script>
import {getHomeInfo,getProfileInfo,getAllShopInfo} from "../request.js";
export default{
name:"HelloWord",
data(){
return{
result:""
}
},
created(){
getHomeInfo().then(res=>{this.result=res;}).catch(err=>{});
getProfileInfo(params).then(res=>{}).catch(err=>{});
getAllShopInfo(params).then(res=>{}).catch(err=>{});
}
}
</script>
到此爲止,axios的基本使用就已經說完。