React Native Http拦截器

Lfa*_*Lfa 10 javascript reactjs swift react-native

像大多数应用程序一样,我正在编写一个在http响应/请求处理程序中需要大量类似逻辑的应用程序.例如,我必须始终检查刷新令牌并将它们保存到AsyncStorage,或者始终将头设置为我的AuthService头,甚至检查404以路由到相同的404错误页面.

我是Angular中http拦截器的忠实粉丝; 你可以在哪里定义和注册一个http拦截器(缺少一个更好的术语)拦截所有的http流量,然后运行组合的通用逻辑.

我有两个主要问题:

  1. 由于在本地做出反应,我们定义这些独立的组件,我们应该不会在第一时间被提取常见的http逻辑,以保持该组件的重用性?
  2. 如果我们不想复制代码,React Native(第一个)或Objective-C/Swift(第二个)是否有办法拦截http流量并为请求提供处理程序?

Ami*_*eli 17

如果你试图仅拦截xhr,你有没有考虑过axios?我正在使用axios拦截器 - https://www.npmjs.com/package/axios ,到目前为止它似乎工作.

这是示例代码

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;
Run Code Online (Sandbox Code Playgroud)

然后导入这个axiosInstance,你想要进行xhr调用