vue axios 簡單封裝以及思考
axios 簡介
axios 是一個基于Promise 用于瀏覽器和 nodejs 的 HTTP 客戶端,它本身具有以下特征:
--------------------------------------------------------------------------------
•從瀏覽器中創(chuàng)建 XMLHttpRequest
•從 node.js 發(fā)出 http 請求
•支持 Promise API
•攔截請求和響應
•轉(zhuǎn)換請求和響應數(shù)據(jù)
•取消請求
•自動轉(zhuǎn)換JSON數(shù)據(jù)
•客戶端支持防止 CSRF/XSRF
先安裝 axios
npm install axios
axios的詳細介紹以及用法 就不多說了請 移步 github ➡️ https://github.com/axios/axios
下面是簡單的封裝一個 http.js, 在此說明 checkStatus 這個方法呢 是不一定需要的 ,根據(jù)個人的項目需求吧,也可以直接返回response,交給后面另行處理也行。
或者根據(jù)后端返回的狀態(tài),在里面進行處理 也行。
"use strict";
import axios from "axios";
import qs from "qs";
//添加請求攔截器
axios.interceptors.request.use(
config => {
return config;
},
error => {
return Promise.reject(error);
}
);
//添加響應攔截器
axios.interceptors.response.use(
response => {
return response;
},
error => {
return Promise.resolve(error.response);
}
);
axios.defaults.baseURL = "https://www.xxxx/api";
axios.defaults.headers.post["Content-Type"] = "application/json";
axios.defaults.headers.post["X-Requested-With"] = "XMLHttpRequest";
axios.defaults.timeout = 10000;
function checkStatus(response) {
return new Promise((resolve, reject) => {
if (
response &&
(response.status === 200 ||
response.status === 304 ||
response.status === 400)
) {
resolve(response.data);
} else {
reject({
state: "0",
message: "網(wǎng)絡異常"
});
}
});
}
export default {
post(url, params) {
return axios({
method: "post",
url,
data: params
}).then(response => {
return checkStatus(response);
});
},
get(url, params) {
params = qs.stringify(params);
return axios({
method: "get",
url,
params
}).then(response => {
return checkStatus(response);
});
}
};
在vue 項目中,main.js這個文件
import http from "./utils/http"; Vue.prototype.$http = http;
使用 helloworld.vue
...
methods: {
async TestPost() {
try {
const res = await this.$http.post("/message/socketid", {
account: "huangenai"
});
console.log(res);
} catch (error) {
console.log(error);
}
},
async TestGet() {
this.$http
.get("/price")
.then(res => {
console.log(res);
})
.catch(error => {
alert(error);
});
}
}
....
在main.js中將http.js import 進來 并暴露到全局使用,在任何vue 頁面中 就不再需要 import http.js了,而直接通過 this.$http.post this.$http.get 來使用,在checkStatus中統(tǒng)一異步返回,順便可以處理錯誤的情況。
個人思考:
checkStatus方法 返回了一個 Promise
鏈式結構的話看上面那個get的方法,this.$http.get(...).then(...).catch(...),如果then 里面又來一個 http請求 會一層包住一層。
如果使用了語法糖 async await ,雖然 看起來好像是簡單了 不用 一層包住一層 層層嵌套,可是你必須要用到 try catch,如果出現(xiàn)異常 則直接到catch,不會再執(zhí)行下面到方法。如果再實際業(yè)務中,就算出現(xiàn)了某一個http請求失敗到情況,不影響下面的邏輯要繼續(xù)跑下去呢,這個就不適用了。鏈式結構也是 如果catch到異常 也不會執(zhí)行then 里面到方法了。
所以,是否把返回的Promise,全部都返回的是 resolve,那么 就不會說出現(xiàn)直接到了 catch 里面不執(zhí)行以下的業(yè)務了邏輯了呢。而且如果使用了語法糖 await 代碼看起來更加簡潔 也不需要 try catch了, 這樣的話 reject是不是就不需要用到了呢。
function checkStatus(response) {
return new Promise(resolve => {
if (
response &&
(response.status === 200 ||
response.status === 304 ||
response.status === 400)
) {
resolve(response.data);
} else {
resolve({
state: "0",
message: "網(wǎng)絡異常"
});
}
});
}
個人覺得這兩種方案各有優(yōu)劣,實際應用中還是應該根據(jù)個人業(yè)務需求 業(yè)務情況而定。
相關文章
Vue實現(xiàn)監(jiān)聽dom節(jié)點寬高變化方式
這篇文章主要介紹了Vue實現(xiàn)監(jiān)聽dom節(jié)點寬高變化方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10
Vue輸入框狀態(tài)切換&自動獲取輸入框焦點的實現(xiàn)方法
這篇文章主要介紹了Vue輸入框狀態(tài)切換&自動獲取輸入框焦點的實現(xiàn),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-05-05

