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

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: "請求錯(cuò)誤,請聯(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)到登錄頁面";
break;
case 3:
message = "TOKEN過期,拒絕訪問,直接跳轉(zhuǎn)到登錄頁面";
break;
case 4:
message = "請求路徑錯(cuò)誤";
break;
case 5:
message = "系統(tǒng)異常,請聯(lián)系管理員";
break;
default:
message = "未知錯(cuò)誤,請聯(lián)系管理員";
break;
}
} else {
if (error.code && error.code == "ECONNABORTED") {
message = "請求超時(shí),請檢查網(wǎng)是否正常";
} else {
message = "未知錯(cuò)誤,請稍后再試";
}
}
return Promise.reject({
code: -1,
message: message,
});
}
);
}
/**
* Http get
* @param url 請求路徑
* @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 請求路徑
* @param data 請求數(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)過vue3項(xiàng)目實(shí)踐,配合mock數(shù)據(jù),使用axios請求基本滿足前端日常開發(fā)的請求方式,至于文件上傳,下載請求,只需要修改請求類型符合前后端聯(lián)調(diào)的功能就可以使用了,對于環(huán)境的配置,我們需要在base_url上面修改指定的域名環(huán)境,這種可以做成配置項(xiàng),比如在process.env.NODE_ENV填寫環(huán)境配置,接下來我將配合http的請求方式詳細(xì)講解網(wǎng)絡(luò)請求的過程,謝謝大家的支持,碼字不易,希望多多三連支持??????
到此這篇關(guān)于vue中使用Axios最佳實(shí)踐的文章就介紹到這了,更多相關(guān)vue使用Axios內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決VUE中document.body.scrollTop為0的問題
今天小編就為大家分享一篇解決VUE中document.body.scrollTop為0的問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09
vue 框架下自定義滾動(dòng)條(easyscroll)實(shí)現(xiàn)方法
這篇文章主要介紹了vue 框架下自定義滾動(dòng)條(easyscroll)實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
Vue項(xiàng)目webpack打包部署到Tomcat刷新報(bào)404錯(cuò)誤問題的解決方案
今天很郁悶,遇到這樣一個(gè)奇葩問題,使用webpack打包vue后,將打包好的文件,發(fā)布到Tomcat上,訪問成功,但是刷新后頁面報(bào)404錯(cuò)誤,折騰半天才解決好,下面小編把Vue項(xiàng)目webpack打包部署到Tomcat刷新報(bào)404錯(cuò)誤問題的解決方案分享給大家,需要的朋友一起看看吧2018-05-05
Vue+Bootstrap實(shí)現(xiàn)簡易學(xué)生管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Vue+Bootstrap實(shí)現(xià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頁面切換項(xiàng)目實(shí)現(xiàn)轉(zhuǎn)場動(dòng)畫的方法
這篇文章主要介紹了vue頁面切換項(xiàng)目實(shí)現(xiàn)轉(zhuǎn)場動(dòng)畫的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
vue+element開發(fā)使用el-select不能回顯的處理方案
這篇文章主要介紹了vue+element開發(fā)使用el-select不能回顯的處理方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(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

