一、基礎使用
使用axios進行客戶端請求,首先需要導入axios的庫文件,可以使用CDN的方式引用也可以npm install之后import進來。
axios的基本用法是在axios.get()中傳入請求地址url,然后返回一個Promise對象,使用.then()方法來處理請求的結果。
axios.get('/api/user')
.then(res => console.log(res.data))
.catch(err => console.error(err));
除了url之外,axios.get()函數接受一個可選的對象參數,包括params、headers、timeout、withCredentials等參數,在后續的小標題中會詳細介紹。
二、傳遞參數
在實際開發中,GET請求需要傳遞參數是非常常見的,比如傳遞用戶名、密碼、頁碼等信息。
以傳遞用戶名為例,可以將用戶名拼接在url路徑后面,如下:
axios.get('/api/user/' + username)
.then(res => console.log(res.data))
.catch(err => console.error(err));
這樣的方式存在一些弊端,比如參數不安全、不方便等。因此,推薦使用params參數,例如:
axios.get('/api/user', { params: { username: 'Tom' } })
.then(res => console.log(res.data))
.catch(err => console.error(err));
這里params參數為一個對象,其中的鍵值對表示請求的參數和對應的值。這種方式不僅是安全的,而且方便管理和維護。
三、URL編碼
當使用params參數傳遞參數時,axios會將參數編碼為url查詢字符串,例如:/api/user?username=Tom。但是,在傳遞一些特殊字符時,可能需要使用URL編碼。
可以使用encodeURIComponent()來編碼參數,例如:
const username = 'Tom & Jerry';
axios.get('/api/user', { params: { username: encodeURIComponent(username) } })
.then(res => console.log(res.data))
.catch(err => console.error(err));
四、Headers參數
Headers參數用于設置請求頭,通常用于身份驗證等。可以使用headers參數傳遞一個對象,其中鍵值對表示請求頭的名稱和對應的值。
axios.get('/api/user', { headers: { Authorization: 'Bearer ' + token } })
.then(res => console.log(res.data))
.catch(err => console.error(err));
這樣可以在請求頭中添加Authorization字段,使用Bearer + token的格式表示身份驗證信息。
五、Timeout參數
Timeout參數用于指定請求的超時時間,單位為毫秒,默認值為0,表示沒有超時時間限制。可以設置一個數字,表示超時時間的毫秒數。
axios.get('/api/user', { timeout: 5000 })
.then(res => console.log(res.data))
.catch(err => console.error(err));
這里的timeout參數表示請求的最長等待時間為5秒,如果超過5秒服務器沒有響應,則請求將被中止。
六、withCredentials參數
withCredentials參數用于指定是否在跨域請求時發送第三方cookie,默認值為false。
axios.get('/api/user', { withCredentials: true })
.then(res => console.log(res.data))
.catch(err => console.error(err));
這里withCredentials參數設為true表示在跨域請求時發送第三方cookie。
七、多個參數
GET請求中同時傳遞多個參數時,可以將多個參數組合成一個對象,然后作為params參數的值傳遞。
axios.get('/api/user', { params: { username: 'Tom', password: '123456' } })
.then(res => console.log(res.data))
.catch(err => console.error(err));
這里將用戶名和密碼都放在了params參數中,以對象形式傳遞。
八、取消請求
在實際開發中,有時需要取消正在進行的請求。可以使用axios.CancelToken來創建一個取消請求的令牌。
const source = axios.CancelToken.source();
axios.get('/api/user', { cancelToken: source.token })
.then(res => console.log(res.data))
.catch(thrown => {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// 處理其他錯誤
}
});
// 取消請求
source.cancel('Operation canceled by the user.');
這里使用axios.CancelToken.source()創建一個令牌作為參數傳遞給axios.get()函數。當需要取消請求時,調用source.cancel()即可。如果請求已經被取消,則將拋出一個錯誤。
九、總結
axios是一個非常強大的客戶端HTTP庫,使用起來非常方便,支持請求和響應攔截器、錯誤處理、取消請求等功能。在GET請求中,使用params、headers、timeout、withCredentials等參數能夠非常方便地實現多種需求。
以上是關于axios GET請求傳參的詳細介紹,相信讀完本文后對axios的使用有更深刻的理解。