Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Http Interceptor

Like most applications, I'm writing an application that requires a lot of similar logic in the http response/requests handlers. For instance, I have to always check for refresh tokens and save them to the AsyncStorage, or always set the headers to my AuthService headers, or even check for 404 to route to the same 404 error page.

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

I have 2 main questions:

  1. Since in React Native, we define these independent components, should we not be extracting common http logic in the first place in order to preserve the re-usability of the component?
  2. If we don't want to duplicate code, is there a way in React Native (first) or Objective-C/Swift (second) to intercept http traffic and provide handlers for the requests?
like image 779
Lfa Avatar asked Jul 08 '15 20:07

Lfa


People also ask

Why do we use Axios interceptors?

Axios interceptors are functions that Axios calls for every request. You can use interceptors to transform the request before Axios sends it, or transform the response before Axios returns the response to your code. You can think of interceptors as Axios' equivalent to middleware in Express or Mongoose.

What is HTTP interceptor in React JS?

The JWT Interceptor intercepts http requests from the React app to add a JWT auth token to the HTTP Authorization header if the user is logged in and the request is to the React app's API URL ( process. env. REACT_APP_API_URL ). It's implemented as an axios request interceptor, by passing a callback function to axios.

How do I submit data to API in react native?

To trigger a Post request from the UI side in react -native, we can send the Request option as a second Parameter. Project Structure: The project should look like this: Example: Here, we are sending request options as a second parameter along with the body. This body is handled in API.


2 Answers

Have you considered axios if you are trying to intercept only xhr? I am using axios interceptors - https://www.npmjs.com/package/axios and so far it seems to work.

Here is the 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

like image 129
Amit Teli Avatar answered Oct 10 '22 05:10

Amit Teli


I'm not sure if I'm understanding this question correctly, or if your looking for more magic, but it sounds like you just want a wrapper to the XMLHttpRequest (or fetch API). Wrap it in a class or a function and you can do whatever you want, whenever you want. Here's an example of an xhr wrapped in a promise:

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();
  });
}

Then you can just use that whenever you want to do HTTP calls...

request("http://blah.com")
  .then(data => console.log(`got data: ${data}`))
  .catch(e => console.error(`error: ${e}`));
like image 31
Mr Speaker Avatar answered Oct 10 '22 06:10

Mr Speaker