vue 專案封裝 axios 的 HTTP 請求
阿新 • • 發佈:2021-02-04
在介紹如何封裝 axios 的 http 請求之前,我們先來了解下什麼是 axios。
axios 是通過 promise 實現對 ajax 技術 的一種封裝,就像 jQuery 實現 ajax 封裝一樣。
簡單來說,ajax 技術實現了網頁的區域性資料重新整理,axios 實現了對 ajax 的封裝。
平時開發 vue 專案時,不同模組都會使用 axios 請求後臺的介面,程式碼如下:
this.$axios({
method: "POST",
url: "介面地址",
params: {
引數名1:"引數值1",
引數名2:"引數值2"
}
}).then(res => {
// 請求成功
}).catch(error=>{
// 請求失敗
});
當請求的介面越來越多時,就會發現寫了很多的重複程式碼,不太利於維護。如果需要使用統一的過濾規則,比如實現超時退出,就需要修改每一個請求的程式碼,非常麻煩。
因此,我們可以封裝一個全域性的HTTP請求,來統一管理後臺介面,封裝步驟如下:
一. 使用 Promise 封裝 HTTP 請求
首先在 src 的 util 資料夾下新建 http.js,使用 Promise 代替回撥函式封裝 HTTP 請求:
http.js 程式碼
import axios from "axios";
var HttpRequest = {
getRequest({ url, data = {}, method = "GET" }) {
return new Promise((resolve, reject) => {
this._getRequest(url, resolve, reject, data, method);
});
},
_getRequest: function(url, resolve, reject, data = {}, method = "GET") {
let format = method.toLocaleLowerCase() ==='get'?'params':'data';
axios({
url: url,
method: method,
[format]: data,
header: {
"content-type": "application/json"
}
}).then(res => {
if (res.status == 200) {
resolve(res);
} else if (res.code == 403) {
// 如果介面返回 403,代表登入超時,跳轉到登入頁面
this.$router.push('/login');
}
}).catch(() => {
reject();
})
}
};
export { HttpRequest };
二. 建立統一管理 API
在 src 的 service 資料夾下新建 auth.js,用於統一管理專案中的許可權相關請求:
auth.js 程式碼
import { HttpRequest } from "../util/http";
let Auth = {
// 判斷使用者名稱稱重複
checkUsername: function(data) {
return HttpRequest.getRequest({
method: "GET",
url: "/api/user/checkUsername",
data: data
});
},
// 使用者註冊
register: function(data) {
return HttpRequest.getRequest({
method: "POST",
url: "/api/user/register",
data: data
});
},
// 獲取使用者資訊
getUserInfo: function(data) {
return HttpRequest.getRequest({
method: "GET",
url: "/api/auth/user/getUserInfo",
data: data
});
},
// 編輯使用者資訊
editUser: function(data) {
return HttpRequest.getRequest({
method: "POST",
url: "/api/auth/user/editUser",
data: data
});
}
};
export {Auth};
三. 呼叫API
在需要進行許可權請求的地方呼叫對應的API:
匯入 API :
import { Auth } from "../service/auth.js";
在方法中實現:
let data = {
username: this.username
};
Auth.checkUsername(data).then(response = > {
if (response.data.code == 200) {
// 使用者名稱重複的對應處理
} else {
// 未重複的對應處理
}
});