javascript - React Native Http Interceptor -
like applications, i'm writing application requires lot of similar logic in http response/requests handlers. instance, have check refresh tokens , save them asyncstorage, or set headers authservice headers, or check 404 route same 404 error page.
i'm big fan of http interceptor in angular; can define , register http interceptor (lack of better term) intercept http traffic , run combined, common logic.
i have 2 main questions:
- since in react native, define these independent components, should not extracting common http logic in first place in order preserve re-usability of component?
- if don't want duplicate code, there way in react native (first) or objective-c/swift (second) intercept http traffic , provide handlers requests?
have considered axios if trying intercept xhr? using axios interceptors - https://www.npmjs.com/package/axios , far seems work.
here sample code
import axios 'axios'; import promise 'promise'; // add request interceptor var axiosinstance = axios.create(); axiosinstance.interceptors.request.use(function (config) { // before request sent //if header not contain token , url not public, redirect login var accesstoken = getaccesstokenfromcookies(); //if token found add header if (accesstoken) { if (config.method !== 'options') { config.headers.authorization = accesstoken; } } return config; }, function (error) { // request error return promise.reject(error); }); export default axiosinstance;
and import axiosinstance ever want make xhr calls
Comments
Post a Comment