axios 套件筆記

官方文檔

如需更多資訊,請參閱 Axios 官方 GitHub 頁面

基本用法

GET 請求

使用 axios.get() 方法來發送 GET 請求。

1
2
3
4
5
6
7
axios.get('https://randomuser.me/api/')
.then(res => {
console.log('success:', res);
})
.catch(err => {
console.log('error:', err);
});

POST 請求

使用 axios.post() 方法來發送 POST 請求,並傳送資料。

1
2
3
4
5
6
7
8
9
10
11
12
const data = {
name: 'John Doe',
email: '[email protected]'
};

axios.post('https://randomuser.me/api/', data)
.then(res => {
console.log('success:', res);
})
.catch(err => {
console.log('error:', err);
});

PATCH 請求

使用 axios.patch() 方法來更新資源。

1
2
3
4
5
6
7
8
9
10
11
const updateData = {
email: '[email protected]'
};

axios.patch('https://randomuser.me/api/1', updateData)
.then(res => {
console.log('success:', res);
})
.catch(err => {
console.log('error:', err);
});

錯誤處理

Axios 提供了 .catch() 方法來處理請求中的錯誤。這使得錯誤管理變得更加方便和直觀。

1
2
3
4
5
6
7
axios.get('https://randomuser.me/api/')
.then(res => {
console.log('success:', res);
})
.catch(err => {
console.error('error:', err);
});

小結

Axios 是一個非常強大的工具,適合用於進行各種 HTTP 請求。它的 Promise-based 結構使得異步操作變得更加簡單。了解如何使用它可以幫助你更有效地進行資料交換和網絡請求。