網站首頁 編程語言 正文
〇、前言
Axios 是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和 Node.js 中。簡單的講就是可以發送 Get、Post 請求。
諸如 Vue、React、Angular 等前端框架都可以使用 Axios,由于他們不操作 DOM,所以就不必須引用 jQuery。如果你的項目里面用了 jQuery,此時就不需要多此一舉了,jQuery 里面本身就可以發送請求($.get(URL,data,function(data,status,xhr),dataType))。
幾個易混淆的概念
- Ajax:Asynchronous JavaScript And XML,翻譯過來就是“異步的 Javascript 和 XML”,屬于一個術語或概念模型,并不特指某一技術,它很重要的特性之一就是讓頁面實現局部刷新,而無需重載整個頁面。
- XHR:XMLHttpRequest 對象用于與服務器交互。通過 XMLHttpRequest 可以在不刷新頁面的情況下請求特定 URL,取的數據后刷新局部頁面。因此,XHR 可以實現 Ajax 請求。
-
Promise:是?ES6 新增的一個對象,是對 XHR 的一種封裝。
它就像一個容器,里面存放著未來才會執行的函數名,處理結果要在異步操作完成后拿到,然后通過 .then() 進行后續操作。
它有三種狀態:Pending(進行中)、Fulfilled(成功)、Rejected(拒絕),進入成功或拒絕的狀態就不會再發生改變。 - Fetch:是在 ES6 出現的,它使用了 ES6 提出的 Promise 對象。是一種網絡請求標準 API。
-
Axios:用于網絡請求的第三方庫,引用后即可用。
使用環境有兩種,一種是在瀏覽器端發送 XHR 請求(中間有一層 Promise 封裝),另一種是在?nodejs 中發送 http 請求,因此利于平臺切換。
支持 Promise API,使用 Promise 管理異步,告別傳統 Callback 方式;豐富的配置項,支持攔截器等高級配置。
注:一兩句話不可能講清楚他們的區別,待后續再慢慢一一展開介紹吧,如有不準確的描述,請評論區指正。
參考:你知道Ajax、Fetch、Axios三者的區別嗎??? ?ajax、Promise、axios總結
回到頂部
一、如何引用?
1、前端項目
// 1、安裝 Axios 庫 |
|
// 在項目文件根目錄下打開命令行,輸入如下語句 |
|
> npm install axios |
|
// 2、js 文件中引入 |
|
import axios from 'axios'; |
|
// 3、直接通過關鍵字 axios 發送 http 請求 |
|
// Get 請求 |
|
axios({ |
|
method: 'get', |
|
url: 'URL文本' |
|
}).then(({data}) => { |
|
// 。。。 |
|
}).catch((err) =>{ |
|
console.log("catch-err:",err); |
|
}).finally(() =>{ |
|
// 。。。 |
|
}) |
|
// Post 請求 |
|
axios({ |
|
headers:{'content-type':'application/json'}, |
|
method: 'post', |
|
url: 'URL文本', |
|
data:JSON.stringify({"dataid":dataid}) |
|
}).then(({data}) => { |
|
console.log("then-data:",data); |
|
}).catch((err) =>{ |
|
console.log("catch-err:",err); |
|
}).finally(() =>{ |
|
// 。。。 |
|
}) |
2、ASP.NET Core MVC 項目
@* 1、引用 js 包的 CDN *@ |
|
<script src="https://unpkg.com/axios/dist/axios.min.js"></script> |
|
@* 2、通過關鍵字 axios 發送 http 請求 *@ |
|
<script> |
|
// 調用方法 message() 查看測試結果 |
|
window.onload = function () { |
|
// Get 請求 |
|
axios.get('https://localhost:44360/api/Methodname', { |
|
params: { |
|
mingcheng: '網絡科技' |
|
}, |
|
headers: { |
|
'token': '1111', |
|
} |
|
} |
|
).then(ret => { |
|
console.log("get:", ret); |
|
}) |
|
// Post 請求 |
|
axios.post('https://localhost:44360/api/Methodname', |
|
{ |
|
"id": "df332b50-4abf-4fe6-814b-6d330a9ecc73", |
|
"gongsix": "線下" |
|
}, |
|
{ |
|
headers: { |
|
'token': '1111', |
|
} |
|
} |
|
).then(ret => { |
|
console.log("post:", ret); |
|
}) |
|
} |
|
</script> |
另外,除了通過 CDN 引用 js 庫外,還可以直接添加 js 文件到項目的靜態文件夾 wwwroot,然后在 .cshtml 頁面文件中用過路徑引用。
簡要的三個步驟如下:
- 下載 js 庫文件。可以直接在網絡上下載,也可以通過通過項目的“管理 NuGet 程序包”來安裝 axios。安裝成功后,找到對應的包右鍵打開“在文件資源管理器中打開文件夾”,按照路徑“Content/Scripts/axios.min.js”找到下載的最新文件。
- 然后復制到“wwwroot/js/...”文件夾下備用。如下圖:
????

??3. 然后通過路徑引用后,即可在 js 腳本中使用 axios。
@* 注意路徑代表 wwwroot 文件夾中,要對應得上 *@ |
|
<script src="~/js/axios/axios.min.js"></script> |
回到頂部
二、語法
參數名 | 示例值 | 解釋 |
url | '/user' | 用于請求的服務器 URL |
method | 'get' | 創建請求時使用的方法,默認 get |
baseURL | 'https://some-domain.com/api/' | 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL(URL 必須帶有資源的完整信息,包含協議、主機、路徑等部分) |
headers | {'X-Requested-With': 'XMLHttpRequest'} | 自定義請求頭 |
params | { ID: 12345 } | URL 參數,會自動拼接到 URL 中 |
data | { firstName: 'Fred' } | 作為請求主體被發送的數據,適用于'PUT'、'POST'、'PATCH' 三個請求方法。在沒有設置 transformRequest 時,必須是以下類型之一:string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams、瀏覽器專屬:FormData, File, Blob、Nodejs專屬:Stream |
timeout | 1000 | 請求超時的毫秒數(0 表示無超時時間),若超時請求將被中斷 |
withCredentials | false | 跨域請求時是否需要使用憑證,默認 false |
responseType | 'json' | 服務器響應的數據類型,可以是 'arraybuffer', 'blob', 'document', 'json'-默認, 'text', 'stream' |
responseEncoding | 'utf8' | 數據編碼類型,默認 utf8 |
maxContentLength | 2000 | 允許的響應內容的最大長度,設置為無限長度:Infinity |
1、Get 請求
以下列舉三種寫法:
// (調用型1)查詢給定 ID 的 user 對象請求 |
|
axios.get('/user?ID=12345') |
|
.then(function (response) { |
|
console.log(response); |
|
}) |
|
.catch(function (error) { |
|
console.log(error); |
|
}); |
|
// (調用型2)另一種寫法 |
|
axios.get('/user', { |
|
params: { |
|
ID: 12345 |
|
} |
|
}) |
|
.then(function (response) { |
|
console.log(response); |
|
}) |
|
.catch(function (error) { |
|
console.log(error); |
|
}); |
|
// (方法型)寫法 |
|
axios({ |
|
method:'get', |
|
url:'/data.json', |
|
params:{ |
|
id:'12345' |
|
} |
|
}).then((res)=>{ |
|
console.log(res) |
|
}) |
?2、Post 請求
?一般上傳的數據分兩種:form-data 表單提交(圖片上傳、文件上傳)、application/json。
// 先定義一個入參 data |
|
let data = { id : 12 } |
|
// (調用型)寫法 |
|
axios.post('/post',data) |
|
}).then((res)=>{ |
|
console.log(res) |
|
}) |
|
// (方法型)寫法 |
|
axios({ |
|
method:'post', |
|
url:'/post', |
|
data:data |
|
}).then((res)=>{ |
|
console.log(res) |
|
}) |
關于 Post 請求的 Content-Type:
當我們直接把入參填入 json 對象,丟給后端接口,此時 Content-Type 就自動為:application/json;charset=UTF-8。
當我們把 json 對象轉為 FormData 類型,如下:
let data = { id : 12 } |
|
let formData = new FormData() |
|
for(let key in data){ |
|
formData.append(key,data[key]) |
|
} |
再將 formData 發送到后端,此時Content-Type 就自動變成:multipart/form-data; boundary=...... 。
3、判斷多個請求全部完成 axios.all(sendAry).then()
// 請求列表,包含多個或多類型請求 |
|
let sendAry = [ |
|
axios.get('URL1'), |
|
axios.get('URL2'), |
|
axios.post('URL3') |
|
]; |
|
// 列表中的請求都完成后,才進行后續操作(可以基于ALL實現) |
|
axios.all(sendAry).then(result => { |
|
console.log(result); // 輸出是一個數組,分別存儲每一個請求的結果 |
|
let [resA, resB, resC] = result; |
|
}); |
4、攔截器
在請求或響應被 then 或 catch 處理前攔截它們。
請求攔截器
axios.interceptors.request.use( |
|
config=>{ |
|
// 在發送請求前做的操作 |
|
return config |
|
}, |
|
err=>{ |
|
// 在請求錯誤的時候做的操作(此處錯誤,請求沒有到后端) |
|
return Promise.reject(err) // 這里返回一個 promise 對象 |
|
} |
|
) |
響應攔截器
axios.interceptors.response.use( |
|
res=>{ |
|
// 請求成功對響應數據進行處理 |
|
return res |
|
},err=>{ |
|
// 響應錯誤做的操作(此處錯誤,到達后端后返回) |
|
return Promise.reject(err) |
|
} |
|
) |
下面的代碼是我們平時發送 Get 請求的標準形態,then 會執行請求成功后的操作,catch 用來捕獲錯誤。我們前面攔截響應后,無論是請求還是響應的攔截器,他們的 err 返回的 promise?都會進入 catch 中。
axios.get().then().catch(err=>{}) |
取消攔截器
let inerceptors = axios.interceptors.request.use |
|
(config=>{ |
|
? ? config.header = { |
|
? ? ? ? auth:true |
|
? ? } |
|
? ? return config |
|
}) |
|
// 如下:用 axios 全局去調用 interceptors,這樣就取消攔截了 |
|
axios.inerceptors.request.eject(interceptors) |
實例:通過攔截器控制登陸狀態
// 登錄狀態,有 token,后端通過 headers 中的 token 進行身份校驗 |
|
let request = axios.create({}) |
|
request.interceptors.request.use |
|
(config => { |
|
? config.headers.token = '' // 發送請求前,統一將 token 加入到請求 headers |
|
? return config |
|
}) |
|
// 非登陸狀態,無 token |
|
let request2 = axios.create({}) |
5、參數配置方法
全局配置
// 兩個實例:(格式類同) |
|
axios.defaults.timeout = 1000 // 全局配置請求時長(單位:毫秒) |
|
axios.defaults.baseURL = 'https://api.example.com'; // 統一配置請求基礎 URL |
實例配置
// 在創建實例時設置默認配置 |
|
const instance = axios.create({ |
|
baseURL: 'https://api.example.com' |
|
}); |
|
// 創建實例后可更改默認值 |
|
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; |
優先級:請求配置 > 實例配置 > 全局配置
6、錯誤處理
// 首先設置兩種攔截器 |
|
axios.interceptors.request.use( |
|
config =>{ |
|
return config |
|
}, |
|
err =>{ |
|
return Promise.reject(err) |
|
} |
|
) |
|
axios.interceptors.response.use( |
|
res =>{ |
|
return res |
|
}, |
|
err =>{ |
|
return Promise.reject(err) |
|
} |
|
) |
|
// 錯誤的獲取 |
|
axios.get('/data.json').then(res=>{ |
|
console.log(res) |
|
}) |
|
.catch(err =>{ |
|
console.log(err) // 所有錯誤處理都會進入此處 |
|
}) |
具體的實踐過程中,我們需要創建一個統一的錯誤處理,將所有的錯誤類型都放在攔截其中,方便我們后面調用接口時使用。
一個實例:
// 創建一個請求實例 |
|
let instance = axios.create({}) |
|
// 為請求實例添加請求攔截器 |
|
instance.interceptors.request.use( |
|
config =>{ |
|
return config |
|
}, |
|
err =>{ |
|
// 請求錯誤,一般 http 狀態碼以 4 開頭,常見:401 超時,404 not found 多為前端瀏覽器錯誤 |
|
return Promise.reject(err) |
|
} |
|
) |
|
instance.interceptors.response.use( |
|
res=>{ |
|
return res |
|
}, |
|
err =>{ |
|
// 響應錯誤,一般 http 狀態碼以 5 開頭,500 系統錯誤,502 系統重啟等,偏向于服務端返回的報錯 |
|
return Promise.reject(err) |
|
} |
|
) |
|
// 使用 |
|
instance.get('/data').then(res=>{ |
|
console.log(res) |
|
}) |
|
.catch(err => { |
|
console.log(err) |
|
}) |
?
原文鏈接:https://blog.csdn.net/2301_78834737/article/details/131588629
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2022-04-28 sql?server?累計求和實現代碼_MsSql
- 2024-02-27 idea中xml文件用瀏覽器打開
- 2022-10-31 Android數據緩存框架內置ORM功能使用教程_Android
- 2023-07-25 使用POI導出Excel
- 2022-03-14 npm 依賴下載報錯 Hostname/IP does not match certificate‘
- 2023-02-10 WPF實現圓形進度條的示例代碼_C#教程
- 2022-06-22 Android開發保存QQ密碼功能_Android
- 2022-05-19 分享Python獲取本機IP地址的幾種方法_python
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支