美文网首页
react-native网络层(axios)统一封装案例

react-native网络层(axios)统一封装案例

作者: 朱传武 | 来源:发表于2021-07-13 23:46 被阅读0次
    import axios from 'axios';
    import Config from '../config/settings';
    import {getStorageKey, KEYS, setStorageKey} from './storage';
    
    const factory = new axios.create({
      timeout: 30000,
      baseURL: Config.BASE_URL,
      headers: {
        'App-Key': Config.APP_KEY,
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/json',
      },
    });
    
    factory.interceptors.request.use(
      async (config) => {
        try {
          console.log(config.headers.Authorization);
          const token = await getStorageKey(KEYS.TOKEN);
    
          const appType = await getStorageKey(KEYS.THERAPY_TYPE);
    
          if (!config.headers.Authorization && token) {
            debugger;
            config.headers.Authorization = `Bearer ${token}`;
          }
          if (!config.headers['App-Type'] && appType) {
            config.headers['App-Type'] = appType;
          }
          console.log('config============');
          console.log(config);
        } catch (e) {
          debugger;
          console.log(e);
          //Not logged in
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      },
    );
    
    factory.interceptors.response.use(
      (response) => response,
      (error) => {
        if (error.response && error.response.status === 401) {
          setStorageKey(KEYS.IS_LOGGED_IN, false);
        }
        return Promise.reject(error.response ? error.response.data : error);
      },
    );
    
    export default factory;
    

    用的时候:

    export const updateUserProfile = (user) => () => {
      return new Promise(async (resolve, reject) => {
        try {
          apiFactory.post('/user/profile/update', {...user}).then(resolve, reject);
        } catch (e) {
          reject(e);
        }
      });
    };
    

    主要是觉得这个拦截器功能比较好用。

    相关文章

      网友评论

          本文标题:react-native网络层(axios)统一封装案例

          本文链接:https://www.haomeiwen.com/subject/lzeepltx.html