Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
173
rated 0 times [  175] [ 2]  / answers: 1 / hits: 29120  / 9 Years ago, wed, july 8, 2015, 12:00:00

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?


More From » swift

 Answers
23

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


[#65879] Monday, July 6, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anais

Total Points: 672
Total Questions: 118
Total Answers: 121

Location: Oman
Member since Fri, Dec 23, 2022
1 Year ago
anais questions
Fri, Jul 29, 22, 00:00, 2 Years ago
Mon, Jul 19, 21, 00:00, 3 Years ago
Tue, May 11, 21, 00:00, 3 Years ago
Fri, Apr 2, 21, 00:00, 3 Years ago
;