Axios
是一個基于 Promise 的 HTTP 客戶端,用于瀏覽器和 Node.js 中發送 HTTP 請求。它提供了一些常用的方法來處理不同類型的請求。以下是 Axios
中常用的一些方法:
1. axios.get()
-
用于發送 GET 請求,從服務器獲取數據。
axios.get('/api/data').then(response => {console.log(response.data);}).catch(error => {console.error(error);});
2. axios.post()
-
用于發送 POST 請求,向服務器發送數據。
axios.post('/api/data', { name: 'John', age: 30 }).then(response => {console.log(response.data);}).catch(error => {console.error(error);});
3. axios.put()
-
用于發送 PUT 請求,更新指定資源的完整數據。
axios.put('/api/data/1', { name: 'John', age: 31 }).then(response => {console.log(response.data);}).catch(error => {console.error(error);});
4. axios.patch()
-
用于發送 PATCH 請求,部分更新指定資源的數據。
axios.patch('/api/data/1', { age: 32 }).then(response => {console.log(response.data);}).catch(error => {console.error(error);});
5. axios.delete()
-
用于發送 DELETE 請求,刪除指定資源。
axios.delete('/api/data/1').then(response => {console.log(response.data);}).catch(error => {console.error(error);});
6. axios.all()
-
用于發送多個并發請求,返回一個 Promise,并且可以在所有請求都完成后執行回調。
axios.all([axios.get('/api/data1'),axios.get('/api/data2') ]) .then(axios.spread((response1, response2) => {console.log(response1.data, response2.data); })) .catch(error => {console.error(error); });
7. axios.create()
-
用于創建一個自定義配置的 Axios 實例,可以復用配置并改變默認的設置(如
baseURL
、headers
、timeout
等)。const instance = axios.create({baseURL: 'https://api.example.com',timeout: 1000,headers: { 'X-Custom-Header': 'foobar' } });instance.get('/data').then(response => {console.log(response.data);}).catch(error => {console.error(error);});
8. axios.interceptors
-
用于攔截請求或響應。你可以使用
request
和response
攔截器來對請求和響應進行處理(例如,設置公共請求頭、處理錯誤等)。請求攔截器:
axios.interceptors.request.use(config => {// 在請求發送前做一些處理config.headers.Authorization = 'Bearer token';return config;},error => {return Promise.reject(error);} );
響應攔截器:
axios.interceptors.response.use(response => {// 處理響應數據return response;},error => {// 錯誤處理return Promise.reject(error);} );
9. axios.getUri()
-
用于獲取請求的 URL,它不會發送請求,只是返回請求的 URL 字符串。
const url = axios.getUri({url: '/api/data',params: {id: 123} }); console.log(url); // 輸出拼接好的完整 URL
10. axios.request()
-
axios.request()
是一個通用的方法,所有 HTTP 請求方法(如get
、post
、put
、delete
)都可以通過該方法來發送。你可以通過傳入配置對象來執行請求。axios.request({url: '/api/data',method: 'get',params: {id: 123} }) .then(response => {console.log(response.data); }) .catch(error => {console.error(error); });
總結:
axios.get()
,axios.post()
,axios.put()
,axios.patch()
,axios.delete()
是常用的 HTTP 方法,用于不同的請求類型。axios.all()
用于處理多個并發請求。axios.create()
用于創建自定義配置的實例。axios.request()
是一個通用方法,可以處理所有類型的請求。axios.interceptors
用于處理請求和響應的攔截器。
這些方法和功能提供了很大的靈活性,可以幫助你在處理 API 請求時更好地管理和優化請求。