# 或者
yarn add axios

創建 API 客戶端文件

讓我們創建一個名為的文件apiClient.js來處理我們的 API 調用:

// apiClient.js 

import axios from 'axios' ;

const BASE_URL = process.env.REACT_APP_BASE_URL || 'https://api.example.com' ; const apiClient = axios.create ({ baseURL : BASE_URL , headers : { 'Content-Type' : ' application /json' , // 你可以在這里添加其他 headers,例如授權令牌 }, }); // 定義常用 API 方法const _get = ( url, config = {} ) => { return apiClient.get (url, config); }; const _delete = ( url, config = {} ) => { return apiClient.delete (url, config ); } ; const _put = ( url, data = {}, config = {} ) => { return apiClient.put (url, data, config); } ; const _post = ( url, data = {}, config = {} ) => { return apiClient.post (url, data, config); } ; // 導出 API 方法export { _get, _delete, _put, _post };

在上面的文件中:

設置環境變量:首先,您需要為不同的環境設置環境變量。通常可以通過.env為每個環境創建文件來完成此操作。例如:

在每個.env文件中,定義你的基本 URL:

REACT_APP_BASE_URL= https://api.example.com

  1. 訪問不同的環境:根據您的環境(例如,開發,QA,暫存),React 將自動加載相應的.env文件,并BASE_URL進行相應的設置。

例如,在開發過程中,React 將加載.env.development,并將BASE_URL其設置為該文件中指定的值。

類似地,在其他環境中(例如 QA、staging),React 將加載相應的.env文件。

2.在 React 組件中的使用:您可以繼續在 React 組件中使用該api對象,如上例所示。基本 URL 將根據環境動態確定。

此設置允許您輕松管理不同環境的不同基本 URL,確保您的 React 應用程序根據其運行的環境與適當的后端進行通信。

在組件中使用 API 客戶端

現在,讓我們看看如何在 React 組件中使用此 API 客戶端:

import  React , { useState, useEffect } from  'react' ; 
import { _get, _post, _put, _delete } from './apiClient' ; // 根據需要調整路徑

function ExampleComponent ( ) {
const [data, setData] = useState ([]);

useEffect ( () => {
// 組件掛載時獲取數據
fetchData ();
}, []);

const fetchData = async ( ) => {
try {
const response = await _get ( '/data' , { headers : { Authorization : 'Bearer your_token_here' } });
setData (response.data ) ;
} catch (error) {
console .error ( '獲取數據時出錯:' , error); // 處理錯誤 } }; const addData = async ( ) => { try { const newData = { name : 'New Item' }; await _post ( '/data' , newData); fetchData (); // 添加后刷新數據 } catch (error) { console.error ( '添加數據錯誤:' , error); // 處理錯誤 } }; const updateData = async ( id, updatedData ) => { try { await _put ( /data/ ${id} , updatedData); fetchData (); // 更新后刷新數據 } catch (error) { console.error ( '更新數據錯誤:' , error ); // 處理錯誤 } }; const deleteData = async ( id ) => { try { await _delete ( /data/ ${id} ); fetchData (); // 刪除后刷新數據 } catch (error) { console.error ( '刪除數據錯誤:' , error); // 處理錯誤 } }; return ( <div> <h1>示例組件</h1> <button onClick={addData}>添加數據</button> <ul> {data.map(item => ( <li key={item.id}> {item.name} <button onClick={() => updateData(item.id, { name: '更新的項目' })}>更新</button> <button onClick={() => deleteData(item.id)}>刪除</button> </li> ))} </ul> </div> ); } export default ExampleComponent ;

在 Axios 中,config參數允許您為 HTTP 請求傳遞額外的配置。一些常見的配置包括標頭、查詢參數、請求超時、身份驗證令牌。

注意:使用 創建 Axios 實例時axios.create()baseURL選項設置為BASE_URL。這意味著使用此 Axios 實例發出的所有請求都將在其 URL 前加上基本 URL 前綴。

例如,如果你_get('/data')從調用ExampleComponent,Axios 將發送一個 GET 請求到'https://api.example.com/data'

結論

使用 Axios 在 React 應用程序中集中 API 調用提供了一種簡潔、有條理的方法來管理 API 邏輯。通過創建集中式 API 客戶端文件,您可以在代碼庫中實現模塊化、組織性和一致性。這種方法簡化了維護并促進了整個應用程序的代碼重用。

上一篇:

使用DeepSeek和Claude繪制出高質量的SVG 圖片

下一篇:

如何獲取Microsoft API Key 密鑰實現bing搜索分步指南
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費