[英]React Native Http Interceptor
像大多數應用程序一樣,我正在編寫一個應用程序,它需要在 http 響應/請求處理程序中有很多類似的邏輯。 例如,我必須始終檢查刷新令牌並將它們保存到 AsyncStorage,或者始終將標頭設置為我的 AuthService 標頭,甚至檢查 404 以路由到相同的 404 錯誤頁面。
我非常喜歡 Angular 中的 http 攔截器; 您可以在其中定義和注冊一個 http 攔截器來(缺乏更好的術語)攔截所有 http 流量,然后運行組合的通用邏輯。
我有兩個主要問題:
如果您只想攔截 xhr,您是否考慮過 axios? 我正在使用 axios 攔截器 - https://www.npmjs.com/package/axios到目前為止它似乎工作。
這是示例代碼
import axios from 'axios';
import promise from 'promise';
// Add a request interceptor
var axiosInstance = axios.create();
axiosInstance.interceptors.request.use(function (config) {
// Do something before request is sent
//If the header does not contain the token and the url not public, redirect to login
var accessToken = getAccessTokenFromCookies();
//if token is found add it to the header
if (accessToken) {
if (config.method !== 'OPTIONS') {
config.headers.authorization = accessToken;
}
}
return config;
}, function (error) {
// Do something with request error
return promise.reject(error);
});
export default axiosInstance;
然后在你想要進行 xhr 調用的地方導入這個 axiosInstance
我不確定我是否正確理解了這個問題,或者您是否正在尋找更多魔法,但聽起來您只是想要一個XMLHttpRequest
(或fetch API
)的包裝器。 將它包裝在一個類或一個函數中,您可以隨時隨地做任何想做的事情。 下面是一個包含在 Promise 中的 xhr 示例:
function request(url, method = "GET") {
const xhr = new XMLHttpRequest();
// Do whatever you want to the xhr... add headers etc
return new Promise((res, rej) => {
xhr.open(method, url);
xhr.onload = () => {
// Do whatever you want on load...
if (xhr.status !== 200) {
return rej("Upload failed. Response code:" + xhr.status);
}
return res(xhr.responseText);
};
xhr.send();
});
}
然后你就可以在你想要進行 HTTP 調用時使用它......
request("http://blah.com")
.then(data => console.log(`got data: ${data}`))
.catch(e => console.error(`error: ${e}`));
你可以使用react-native-easy-app更容易發送http請求和制定攔截請求
import {XHttpConfig} from 'react-native-easy-app';
XHttpConfig.initHttpLogOn(true) // Print the Http request log or not
.initBaseUrl(ApiCredit.baseUrl) // BaseUrl
.initContentType(RFApiConst.CONTENT_TYPE_URLENCODED)
.initHeaderSetFunc((headers, request) => {
// Set the public header parameter here
})
.initParamSetFunc((params, request) => {
// Set the public params parameter here
})
.initParseDataFunc((result, request, callback) => {
let {success, json, response, message, status} = result;
// Specifies the specific data parsing method for the current app
});
* Synchronous request
const response = await XHttp().url(url).execute('GET');
const {success, json, message, status} = response;
* Asynchronous requests
XHttp().url(url).get((success, json, message, status)=>{
if (success){
this.setState({content: JSON.stringify(json)});
} else {
showToast(msg);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.