我有一個反應原生專案,在對我的后端進行經過身份驗證的呼叫時,它依賴于從 SecureStorage 獲取憑據。與正常反應不同,這是一個異步程序,這意味著我每次需要標頭時都必須處理承諾。由于我每次都需要阻止獲取憑據,但不應該/不能強制異步同步,這意味著很多不必要的代碼(鏈接“thens”或進行遠程呼叫異步/等待)。有沒有更優雅的方式來處理這種情況?
我能想到的兩個選項是 1.) 每次處理承諾或 2.) 傳入具有全域背景關系的 auth 標頭。
這是我所擁有的一個例子
useFeedFetch = (payload: GetItemsRequest) => {
// misc state set here
useEffect(() => {
const getFeedAsync = async () => {
// gets credentials from secure storage
let headers = await AuthService.getAuthHeader()
axios({
method: 'POST',
url: requestUrl,
headers: headers,
data: payload,
}).then((res) => {
...
}
}
getFeedAsync()
}
, [payload.page]);
return {
loading, error, items, hasMore,
};
uj5u.com熱心網友回復:
您當然可以通過使用Axios 攔截器來使其更加不可見
// eg api.js
import axios from "axios"
import AuthService from "wherever"
// create a new instance to include your interceptor
export const api = axios.create({
// baseURL can be handy to shorten your URLs
})
api.interceptors.request.use(async config => ({
...config,
headers: {
...config.headers,
...await AuthService.getAuthHeader()
}
}))
現在您可以使用api代替,axios它會自動在每個請求上應用您的身份驗證標頭
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/431308.html
標籤:javascript 反应式 axios
上一篇:EFCoreDbDataReader結果在攔截器中發生變化
下一篇:(TypeScript,reactnative)setTimeout結合onPressIn和onPressOut
