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:

  1. since in react native, define these independent components, should not extracting common http logic in first place in order preserve re-usability of component?
  2. 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

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -