Respond to HTTP Interceptor

Like most applications, I am writing an application that requires a lot of similar logic in HTTP / request response handlers. For example, I should always check for update tokens and save them in AsyncStorage, or always set headers in AuthService headers, or even check that 404 goes to the same 404 error page.

I am a big fan of the http interceptor in Angular; where you can define and register an http interceptor (lack of a better term), intercept all http traffic, and then run the combined common logic.

I have two main questions:

  • Since we define these independent components in React Native, should we not extract the general HTTP logic in the first place to preserve component reuse?
  • If we don’t want to duplicate the code, is there a way in React Native (first) or Objective-C / Swift (second) to intercept HTTP traffic and provide request handlers?
+4
source share
2 answers

Did you consider axioms if you are trying to intercept only xhr? I use axios interceptors - https://www.npmjs.com/package/axios and for now it works.

Here is a sample code

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;

and then import this axiosInstance where ever you want to make xhr calls

+7
source

, , , , XMLHttpRequest ( fetch API). , , , , . 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}`));
+1

All Articles