React Native Http Interceptor React Native Http Interceptor reactjs reactjs

React Native Http Interceptor


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


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


you can use react-native-easy-app that is easier to send http request and formulate interception request

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 requestconst response = await XHttp().url(url).execute('GET');const {success, json, message, status} = response;* Asynchronous requestsXHttp().url(url).get((success, json, message, status)=>{    if (success){       this.setState({content: JSON.stringify(json)});    } else {       showToast(msg);    }});