vue中使用Axios最佳實(shí)踐方式
1.前言
最近在寫(xiě)vue3的項(xiàng)目,需要重新搭建腳手架并且使用網(wǎng)絡(luò)請(qǐng)求接口,對(duì)于js的網(wǎng)絡(luò)請(qǐng)求接口的一般有幾種常用的方式:
- fetch
- XMLHttpRequests
- ajax (原生)
- axios (開(kāi)源)
Axios 是一個(gè)基于 promise 的網(wǎng)絡(luò)請(qǐng)求庫(kù),可以用于瀏覽器和 node.js。Axios 使用簡(jiǎn)單,包尺寸小且提供了易于擴(kuò)展的接口。在服務(wù)端它使用原生 node.jshttp模塊, 而在客戶端 (瀏覽端) 則使用 XMLHttpRequests。
簡(jiǎn)單示例:
import axios from "axios";
axios.get('/users')
.then(res => {
console.log(res.data);
});2.使用
2.1安裝
npm install axios
2.2基本用例
在commonJs中使用axios時(shí)候:使用require()導(dǎo)入的時(shí)候獲得ts的類(lèi)型推斷;使用以下方法:
const axios = require('axios').default;
// axios.<method> 能夠提供自動(dòng)完成和參數(shù)類(lèi)型推斷功能
2.2.1 get請(qǐng)求
發(fā)送一個(gè)get請(qǐng)求
import axios from "axios";
axios
.get("/getData")
.then((res) => {
console.log(res);
list.value = res.data.list;
})
.catch(function (error) {
// 處理錯(cuò)誤情況
console.log(error);
})
.then(function () {
// 總是會(huì)執(zhí)行
});支持異步操作async/await用法
const list = ref<ListModel[]>([]);
async function getUrl() {
const res = await axios.get("/getData", {
params: {
id: 1, //需要攜帶參數(shù)
},
});
list.value = res.data.list;
}
getUrl();2.2.2post請(qǐng)求
發(fā)送一個(gè)post請(qǐng)求
function postUrl() {
axios
.post("/postData", {
name: "Fred",
age: 18,
})
.then(function (response) {
console.log(response.data.message);
})
.catch(function (error) {
console.log(error);
});
}
postUrl();發(fā)起多個(gè)并發(fā)請(qǐng)求
// 發(fā)送多個(gè)并發(fā)請(qǐng)求
function getUserInfo() {
return axios.get("/userInfo");
}
function getToken() {
return axios.get("/getToken");
}
//同步
Promise.all([getUserInfo(), getToken()]).then((res) => {
console.log(res, "res");
});
//異步
Promise.race([getUserInfo(), getToken()]).then((res) => {
console.log(res, "res1111");
});3.配置
3.1語(yǔ)法
axios(config)
// 發(fā)起一個(gè)post請(qǐng)求
axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } });
默認(rèn)請(qǐng)求方式:
// 發(fā)起一個(gè) GET 請(qǐng)求 (默認(rèn)請(qǐng)求方式) axios('/user/12345');
3.2別名
axios.request(config)
4.Axios實(shí)例
4.1語(yǔ)法
axios.create([config])
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});4.2請(qǐng)求配置
這些是創(chuàng)建請(qǐng)求時(shí)可以用的配置選項(xiàng)。只有url是必需的。如果沒(méi)有指定method,請(qǐng)求將默認(rèn)使用GET方法。
{
// `url` 是用于請(qǐng)求的服務(wù)器 URL
url: '/user',
// `method` 是創(chuàng)建請(qǐng)求時(shí)使用的方法
method: 'get', // 默認(rèn)值
// `baseURL` 將自動(dòng)加在 `url` 前面,除非 `url` 是一個(gè)絕對(duì) URL。
// 它可以通過(guò)設(shè)置一個(gè) `baseURL` 便于為 axios 實(shí)例的方法傳遞相對(duì) URL
baseURL: 'https://some-domain.com/api/',
// `transformRequest` 允許在向服務(wù)器發(fā)送前,修改請(qǐng)求數(shù)據(jù)
// 它只能用于 'PUT', 'POST' 和 'PATCH' 這幾個(gè)請(qǐng)求方法
// 數(shù)組中最后一個(gè)函數(shù)必須返回一個(gè)字符串, 一個(gè)Buffer實(shí)例,ArrayBuffer,F(xiàn)ormData,或 Stream
// 你可以修改請(qǐng)求頭。
transformRequest: [function (data, headers) {
// 對(duì)發(fā)送的 data 進(jìn)行任意轉(zhuǎn)換處理
return data;
}],
// `transformResponse` 在傳遞給 then/catch 前,允許修改響應(yīng)數(shù)據(jù)
transformResponse: [function (data) {
// 對(duì)接收的 data 進(jìn)行任意轉(zhuǎn)換處理
return data;
}],
// 自定義請(qǐng)求頭
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` 是與請(qǐng)求一起發(fā)送的 URL 參數(shù)
// 必須是一個(gè)簡(jiǎn)單對(duì)象或 URLSearchParams 對(duì)象
params: {
ID: 12345
},
// `data` 是作為請(qǐng)求體被發(fā)送的數(shù)據(jù)
// 僅適用 'PUT', 'POST', 'DELETE 和 'PATCH' 請(qǐng)求方法
// 在沒(méi)有設(shè)置 `transformRequest` 時(shí),則必須是以下類(lèi)型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - 瀏覽器專(zhuān)屬: FormData, File, Blob
// - Node 專(zhuān)屬: Stream, Buffer
data: {
firstName: 'Fred'
},
// `timeout` 指定請(qǐng)求超時(shí)的毫秒數(shù)。
// 如果請(qǐng)求時(shí)間超過(guò) `timeout` 的值,則請(qǐng)求會(huì)被中斷
timeout: 1000, // 默認(rèn)值是 `0` (永不超時(shí))
// `withCredentials` 表示跨域請(qǐng)求時(shí)是否需要使用憑證
withCredentials: false, // default
// `auth` HTTP Basic Auth
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` 表示瀏覽器將要響應(yīng)的數(shù)據(jù)類(lèi)型
// 選項(xiàng)包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
// 瀏覽器專(zhuān)屬:'blob'
responseType: 'json', // 默認(rèn)值
// `responseEncoding` 表示用于解碼響應(yīng)的編碼 (Node.js 專(zhuān)屬)
// 注意:忽略 `responseType` 的值為 'stream',或者是客戶端請(qǐng)求
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // 默認(rèn)值
// `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名稱(chēng)
xsrfCookieName: 'XSRF-TOKEN', // 默認(rèn)值
// `xsrfHeaderName` 是帶有 xsrf token 值的http 請(qǐng)求頭名稱(chēng)
xsrfHeaderName: 'X-XSRF-TOKEN', // 默認(rèn)值
// `onUploadProgress` 允許為上傳處理進(jìn)度事件
// 瀏覽器專(zhuān)屬
onUploadProgress: function (progressEvent) {
// 處理原生進(jìn)度事件
},
// `onDownloadProgress` 允許為下載處理進(jìn)度事件
// 瀏覽器專(zhuān)屬
onDownloadProgress: function (progressEvent) {
// 處理原生進(jìn)度事件
},
// `maxContentLength` 定義了node.js中允許的HTTP響應(yīng)內(nèi)容的最大字節(jié)數(shù)
maxContentLength: 2000,
// `maxBodyLength`(僅Node)定義允許的http請(qǐng)求內(nèi)容的最大字節(jié)數(shù)
maxBodyLength: 2000,
// `validateStatus` 定義了對(duì)于給定的 HTTP狀態(tài)碼是 resolve 還是 reject promise。
// 如果 `validateStatus` 返回 `true` (或者設(shè)置為 `null` 或 `undefined`),
// 則promise 將會(huì) resolved,否則是 rejected。
validateStatus: function (status) {
return status >= 200 && status < 300; // 默認(rèn)值
},
// `maxRedirects` 定義了在node.js中要遵循的最大重定向數(shù)。
// 如果設(shè)置為0,則不會(huì)進(jìn)行重定向
maxRedirects: 5, // 默認(rèn)值
// `proxy` 定義了代理服務(wù)器的主機(jī)名,端口和協(xié)議。
// 您可以使用常規(guī)的`http_proxy` 和 `https_proxy` 環(huán)境變量。
// 使用 `false` 可以禁用代理功能,同時(shí)環(huán)境變量也會(huì)被忽略。
// `auth`表示應(yīng)使用HTTP Basic auth連接到代理,并且提供憑據(jù)。
// 這將設(shè)置一個(gè) `Proxy-Authorization` 請(qǐng)求頭,它會(huì)覆蓋 `headers` 中已存在的自定義 `Proxy-Authorization` 請(qǐng)求頭。
// 如果代理服務(wù)器使用 HTTPS,則必須設(shè)置 protocol 為`https`
proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// see https://axios-http.com/zh/docs/cancellation
cancelToken: new CancelToken(function (cancel) {
}),
}4.3響應(yīng)的配置
一個(gè)請(qǐng)求的響應(yīng)包含以下信息
{
// `data` 由服務(wù)器提供的響應(yīng)
data: {},
// `status` 來(lái)自服務(wù)器響應(yīng)的 HTTP 狀態(tài)碼
status: 200,
// `statusText` 來(lái)自服務(wù)器響應(yīng)的 HTTP 狀態(tài)信息
statusText: 'OK',
// `headers` 是服務(wù)器響應(yīng)頭
// 所有的 header 名稱(chēng)都是小寫(xiě),而且可以使用方括號(hào)語(yǔ)法訪問(wèn)
// 例如: `response.headers['content-type']`
headers: {},
// `config` 是 `axios` 請(qǐng)求的配置信息
config: {},
// `request` 是生成此響應(yīng)的請(qǐng)求
// 在node.js中它是最后一個(gè)ClientRequest實(shí)例 (in redirects),
// 在瀏覽器中則是 XMLHttpRequest 實(shí)例
request: {}
}配置的優(yōu)先級(jí)
配置將會(huì)按優(yōu)先級(jí)進(jìn)行合并。它的順序是:在lib/defaults.js中找到的庫(kù)默認(rèn)值,然后是實(shí)例的defaults屬性,最后是請(qǐng)求的config參數(shù)。后面的優(yōu)先級(jí)要高于前面的。下面有一個(gè)例子。
// 使用庫(kù)提供的默認(rèn)配置創(chuàng)建實(shí)例
// 此時(shí)超時(shí)配置的默認(rèn)值是 `0`
const instance = axios.create();
// 重寫(xiě)庫(kù)的超時(shí)默認(rèn)值
// 現(xiàn)在,所有使用此實(shí)例的請(qǐng)求都將等待2.5秒,然后才會(huì)超時(shí)
instance.defaults.timeout = 2500;
// 重寫(xiě)此請(qǐng)求的超時(shí)時(shí)間,因?yàn)樵撜?qǐng)求需要很長(zhǎng)時(shí)間
instance.get('/longRequest', {
timeout: 5000
});5.攔截器
在請(qǐng)求或響應(yīng)被 then 或 catch 處理前攔截它們。
// 生成實(shí)例
const instance = axios.create({
baseURL: "/",
timeout: 1000,
headers: { "Content-Type": "multipart/form-data;charset=utf-8" },
});
// 請(qǐng)求的攔截器
instance.interceptors.request.use(
function (config) {
// 在發(fā)送請(qǐng)求之前做些什么
console.log(config, "config");
return config;
},
function (error) {
// 對(duì)請(qǐng)求錯(cuò)誤做些什么
return Promise.reject(error);
}
);
// 返回的攔截器
instance.interceptors.response.use(
function (res) {
// 2xx 范圍內(nèi)的狀態(tài)碼都會(huì)觸發(fā)該函數(shù)。
// 對(duì)響應(yīng)數(shù)據(jù)做點(diǎn)什么
console.log(res, "res");
return res;
},
function (error) {
// 超出 2xx 范圍的狀態(tài)碼都會(huì)觸發(fā)該函數(shù)。
// 對(duì)響應(yīng)錯(cuò)誤做點(diǎn)什么
return Promise.reject(error);
}
);6.錯(cuò)誤攔截
axios.get('/getData')
.catch(function (error) {
if (error.response) {
// 請(qǐng)求成功發(fā)出且服務(wù)器也響應(yīng)了狀態(tài)碼,但狀態(tài)代碼超出了 2xx 的范圍
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// 請(qǐng)求已經(jīng)成功發(fā)起,但沒(méi)有收到響應(yīng)
// `error.request` 在瀏覽器中是 XMLHttpRequest 的實(shí)例,
// 而在node.js中是 http.ClientRequest 的實(shí)例
console.log(error.request);
} else {
// 發(fā)送請(qǐng)求時(shí)出了點(diǎn)問(wèn)題
console.log('Error', error.message);
}
console.log(error.config);
});使用validateStatus配置選項(xiàng),可以自定義拋出錯(cuò)誤的 HTTP code。
axios.get('/getData', {
validateStatus: function (status) {
return status < 500; // 處理狀態(tài)碼小于500的情況
}
})使用toJSON可以獲取更多關(guān)于HTTP錯(cuò)誤的信息。
const controller = new AbortController();
axios.get('/getData', {
signal: controller.signal
}).then(function(response) {
//...
});
// 取消請(qǐng)求
controller.abort()7.取消請(qǐng)求
從v0.22.0以后,CancelToken取消請(qǐng)求的方式被棄用,Axios 支持以 fetch API 方式——AbortController取消請(qǐng)求:
const controller = new AbortController();
axios.get('/getData', {
signal: controller.signal
}).then(function(response) {
//...
});
// 取消請(qǐng)求
controller.abort()8.完整封裝 建立http.ts文件編寫(xiě)clas Http類(lèi)
完整代碼如下,親自測(cè)試通過(guò):

http.ts文件全部代碼如下:
import type { AxiosInstance, AxiosRequestConfig } from "axios";
import axios from "axios";
class Http {
private readonly options: AxiosRequestConfig;
private axiosInstance: AxiosInstance;
// 構(gòu)造函數(shù) 參數(shù) options
constructor(params: AxiosRequestConfig) {
this.options = params;
this.axiosInstance = axios.create(params); // 生成實(shí)例
this.setupInterceptors();
}
private setupInterceptors() {
this.axiosInstance.defaults.baseURL = "/";
this.axiosInstance.defaults.headers.post["Content-Type"] =
"application/json";
this.axiosInstance.interceptors.request.use(
(config) => {
if (!config.headers) {
config.headers = {};
}
// config.headers.Authorization = CSRF_TOKEN;
return config;
},
() => {
return Promise.reject({
code: 1,
message: "請(qǐng)求錯(cuò)誤,請(qǐng)聯(lián)系管理員",
});
}
);
this.axiosInstance.interceptors.response.use(
(response) => {
return Promise.resolve(response);
},
(error) => {
let message = "";
if (error.response) {
switch (error.response.status) {
case 2:
message = "未登錄,直接跳轉(zhuǎn)到登錄頁(yè)面";
break;
case 3:
message = "TOKEN過(guò)期,拒絕訪問(wèn),直接跳轉(zhuǎn)到登錄頁(yè)面";
break;
case 4:
message = "請(qǐng)求路徑錯(cuò)誤";
break;
case 5:
message = "系統(tǒng)異常,請(qǐng)聯(lián)系管理員";
break;
default:
message = "未知錯(cuò)誤,請(qǐng)聯(lián)系管理員";
break;
}
} else {
if (error.code && error.code == "ECONNABORTED") {
message = "請(qǐng)求超時(shí),請(qǐng)檢查網(wǎng)是否正常";
} else {
message = "未知錯(cuò)誤,請(qǐng)稍后再試";
}
}
return Promise.reject({
code: -1,
message: message,
});
}
);
}
/**
* Http get
* @param url 請(qǐng)求路徑
* @param config 配置信息
* @returns Promise
*/
get(url: string, config?: any): Promise<any> {
return new Promise((resolve, reject) => {
this.axiosInstance
.get(url, config)
.then((response) => {
resolve(response.data);
})
.catch((error) => {
reject(error);
});
});
}
/**
* Http post
* @param url 請(qǐng)求路徑
* @param data 請(qǐng)求數(shù)據(jù)
* @param config 配置
* @returns Promise
*/
post(url: string, data?: any, config?: any): Promise<any> {
return new Promise((reslove, reject) => {
this.axiosInstance
.post(url, data, config)
.then((response) => {
reslove(response.data);
})
.catch((error) => {
reject(error);
});
});
}
}
const http = new Http({
timeout: 1000 * 5,
});
export default http;9.總結(jié)
個(gè)人經(jīng)過(guò)vue3項(xiàng)目實(shí)踐,配合mock數(shù)據(jù),使用axios請(qǐng)求基本滿足前端日常開(kāi)發(fā)的請(qǐng)求方式,至于文件上傳,下載請(qǐng)求,只需要修改請(qǐng)求類(lèi)型符合前后端聯(lián)調(diào)的功能就可以使用了,對(duì)于環(huán)境的配置,我們需要在base_url上面修改指定的域名環(huán)境,這種可以做成配置項(xiàng),比如在process.env.NODE_ENV填寫(xiě)環(huán)境配置,接下來(lái)我將配合http的請(qǐng)求方式詳細(xì)講解網(wǎng)絡(luò)請(qǐng)求的過(guò)程,謝謝大家的支持,碼字不易,希望多多三連支持??????
到此這篇關(guān)于vue中使用Axios最佳實(shí)踐的文章就介紹到這了,更多相關(guān)vue使用Axios內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決VUE中document.body.scrollTop為0的問(wèn)題
今天小編就為大家分享一篇解決VUE中document.body.scrollTop為0的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-09-09
vue 框架下自定義滾動(dòng)條(easyscroll)實(shí)現(xiàn)方法
這篇文章主要介紹了vue 框架下自定義滾動(dòng)條(easyscroll)實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
Vue項(xiàng)目webpack打包部署到Tomcat刷新報(bào)404錯(cuò)誤問(wèn)題的解決方案
今天很郁悶,遇到這樣一個(gè)奇葩問(wèn)題,使用webpack打包vue后,將打包好的文件,發(fā)布到Tomcat上,訪問(wèn)成功,但是刷新后頁(yè)面報(bào)404錯(cuò)誤,折騰半天才解決好,下面小編把Vue項(xiàng)目webpack打包部署到Tomcat刷新報(bào)404錯(cuò)誤問(wèn)題的解決方案分享給大家,需要的朋友一起看看吧2018-05-05
Vue+Bootstrap實(shí)現(xiàn)簡(jiǎn)易學(xué)生管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Vue+Bootstrap實(shí)現(xiàn)簡(jiǎn)易學(xué)生管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-02-02
Vue實(shí)現(xiàn)根據(jù)hash高亮選項(xiàng)卡
這篇文章主要為大家詳細(xì)介紹了Vue實(shí)現(xiàn)根據(jù)hash高亮選項(xiàng)卡,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-05-05
vue頁(yè)面切換項(xiàng)目實(shí)現(xiàn)轉(zhuǎn)場(chǎng)動(dòng)畫(huà)的方法
這篇文章主要介紹了vue頁(yè)面切換項(xiàng)目實(shí)現(xiàn)轉(zhuǎn)場(chǎng)動(dòng)畫(huà)的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
vue+element開(kāi)發(fā)使用el-select不能回顯的處理方案
這篇文章主要介紹了vue+element開(kāi)發(fā)使用el-select不能回顯的處理方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07
Vue中 Runtime + Compiler 和 Runtime-o
這篇文章主要介紹了Vue中 Runtime + Compiler 和 Runtime-only 兩種模式含義和區(qū)別,結(jié)合實(shí)例形式詳細(xì)分析了Vue中 Runtime + Compiler 和 Runtime-only 兩種模式基本功能、原理、區(qū)別與相關(guān)注意事項(xiàng),需要的朋友可以參考下2023-06-06

