在 React.js 中發起 HTTP 請求
在一個典型的 Web 應用中,客戶端透過瀏覽器發出 HTTP 請求,伺服器在響應中傳送包含資料的 HTML 頁面。
但在單頁應用程式 (SPA) 中,我們只有一個頁面,每當客戶端向伺服器發出 HTTP 請求時,伺服器通常會以 JSON/XML 格式的資料進行響應。
為了發出 HTTP 請求,我們有一些如下選項:
- XmlHttpRequest
- Axios
- Windows fetch
Axios 易於與 React 整合並處理請求。
讓我們先安裝它
npm install –save axios
在使用前將其匯入 jsx 檔案
import Axios from ‘axios’;
從元件生命週期文章中,我們觀察到 componentDidMount 是進行副作用(例如發出 HTTP 請求)的最佳位置。因為 componentDidMount 在元件的生命週期中只執行一次。一旦 HTTP 請求完成,我們就可以非同步更新我們的狀態,頁面將使用這些更新重新渲染。
Axios 使用 Promise 以非同步方式工作。
componentDidMount(){
Axios.get(‘url’).then((response)=>{console.log(response)});
}然後函式簡單地包含一個函式,該函式的引數是來自 Promise 的響應。在 then 中,我們可以使用 setState 將資料更新到類的狀態物件。
我們可以在 componentDidMount 中更新實際狀態之前操作資料。此外,我們可以在 Axios 中傳送查詢引數。
根據狀態的一些變化,如果我們想發出另一個 HTTP 請求,那麼我們應該使用 componentDidUpdate。但是我們必須確保透過新增條件邏輯不會導致無限迴圈。例如,使用 ID 作為引數,我們可以檢查它是否與之前的 ID 不相等,然後我們可以在此處發出新的 HTTP 請求。
發出 POST 請求
與 GET 請求類似,我們可以在按鈕點選時發出 POST 請求。
postdata=()=>{
const postObject={
//values
}
Axios.post(‘url’, postObject).then(response=>{ //process the response});
}與 GET 類似,我們在 POST 請求完成後獲得 Promise。還有其他 HTTP 方法可以以相同的方式執行。
deleteData=()=>{
Axios.delete(‘url’).then(response=>{});
}使用 Axios 處理錯誤
我們在 then 方法之後有 catch 方法。
Axios.get(‘url’).then(response=>{}).catch(error=>{
//we can update state to an error to show meaningful message on screen
});全域性新增 Axios 攔截器
有時我們需要一個公共流程,例如在發出 HTTP 請求處理時新增身份驗證資料或日誌記錄。
在 index.js 檔案中,我們可以新增攔截器,這些攔截器將可用於所有 Axios 配置。
Index.js
Import axios from ‘axios’;
Axios.interceptors.request.use(request=>{
//add logic here on the coming request
return request;
});確保在攔截器中也返回請求。我們也可以新增錯誤邏輯,如下所示
Axios.interceptors.request.use(request=>{
//add logic here on the coming request
return request;
}, error=>{
//add error specific logic
return Promise.reject(error);
});同樣,我們可以為響應新增攔截器
Axios.interceptors. response.use(response=>{
//add logic here on the coming response
return response;
}, error=>{
//add error specific logic
return Promise.reject(error);
});我們可以為 Axios 進行其他全域性配置,例如為所有請求設定基本 URL。
在 index.js 檔案中新增以下行
Axios.defaults.baseURL=’your base url’;
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP