RN-Axios-如何在传奇中添加axios拦截器-React Native

时间:2018-07-09 14:20:13

标签: reactjs react-native axios redux-saga

saga中的代码段如下所示

async componentDidMount() {

  try {
    const value = await AsyncStorage.getItem(REFRESH_TOKEN);
    if (value !== null) {
      // We have data!!
      console.log(value);
      this.setState({
        refreshToken: value
      })
    }
  } catch (error) {
    // Error retrieving data
  }
  //running interceptor
  const self = this;
  axios.interceptors.response.use(function(response) {
    // Do something with response data
    // console.log('response in interceptor', response);
    return response
  }, function(error) {
    const originalRequest = error.config;
    // Do something with response error
    console.log(JSON.stringify(error));
    console.log('error==================================', error.response.data.error);


    if (error.response.status === 401 && error.response.data.error === 'invalid_token') { //custom error checking based on the data i get

      console.log('hit error');

      originalRequest._retry = true
      const retryOrigReq = new Promise((resolve, reject) => {
        axios.post(REFRESH_TOKEN_URL, null) //give ur refrsh token url 
          .then((resp) => {
            // console.log(resp)
            self.setState({
              token: resp.data.access_token
            });
            try {
              AsyncStorage.setItem('AUTH_TOKEN', 'bearer ' + resp.data.access_token);
            } catch (error) {
              // Error saving data
            }
            try {
              AsyncStorage.setItem('REFRESH_TOKEN', resp.data.refresh_token);
            } catch (error) {
              // Error saving data
            }
            originalRequest.headers['Authorization'] = 'Bearer ' + resp.data.access_token
            resolve(axios(originalRequest));
          })
          .catch((error) => {
            console.log(error);
          })
      });
      return retryOrigReq;
    } else {
      return Promise.reject(error);
    }
  });
}

我该如何附加axios响应拦截器,以便我可以检查令牌是否已过期,以及是否已过期,我将必须发送刷新令牌才能获取新的访问令牌。在这种情况下如何使用axios拦截器?


自己解决了代码如下

@Pipe({name: 'groupByDate'})
export class GroupByPipe implements PipeTransform {
transform(collection: Array<any>, property: string = 'date'): Array<any> {
    if(!collection) {
        return null;
    }
    const gc = collection.reduce((previous, current)=> {
        if(!previous[current[property]]) {
            previous[current[property]] = [];
        }
            current.events.forEach(x => previous[current[property]].push(x));
        return previous;
    }, {});
    return Object.keys(gc).map(date => ({ date: date, events: gc[date] }));
    }  
}

2 个答案:

答案 0 :(得分:0)

您需要分别添加一个 axios 实例,在该实例上添加一个拦截器,然后在您应用的其他部分上使用该实例。

Interceptor.js

import axios from 'axios'
import {SERVER_URL} from '../Config'
import {path} from 'ramda'

import AuthService from './AuthService' // ... Just a service to refresh auth tokens

const AxiosInstance = axios.create({
    baseURL: SERVER_URL,
    timeout: 20000,
    headers: {
        'Content-Type': 'application/json'
    }
})

AxiosInstance.interceptors.response.use((response) =>{
    return response;
}, (error) => {
    const originalRequest = error.config;
    if (!error.response) {
       return Promise.reject('Network Error')
    }
    else if ((error.response.status === 401) && !originalRequest._retry) {
        originalRequest._retry = true;
        return AuthService.getToken()
            .then(token => {
                const authTokenResponse = path(['data', 'response'], token)
                AxiosInstance.defaults.headers.common['Authorization'] = 'Bearer ' + authTokenResponse;
                originalRequest.headers['Authorization'] = 'Bearer ' + authTokenResponse;
                return axios(originalRequest);
            })
            .catch(err => err)
    } else {
        return error.response
    }

})

export default AxiosInstance

Services.js

import AxiosInstance from './Interceptor' // ... Your Interceptor path
const register = (params) =>
    AxiosInstance.get('// Some Sample Url')
        .catch(error => error) // Either handle the error here or in the sagas

Sagas.js

然后在您的sagas中访问服务。

答案 1 :(得分:-2)

async componentDidMount() {

  try {
    const value = await AsyncStorage.getItem(REFRESH_TOKEN);
    if (value !== null) {
      // We have data!!
      console.log(value);
      this.setState({
        refreshToken: value
      })
    }
  } catch (error) {
    // Error retrieving data
  }
  //running interceptor
  const self = this;
  axios.interceptors.response.use(function(response) {
    // Do something with response data
    // console.log('response in interceptor', response);
    return response
  }, function(error) {
    const originalRequest = error.config;
    // Do something with response error
    console.log(JSON.stringify(error));
    console.log('error==================================', error.response.data.error);


    if (error.response.status === 401 && error.response.data.error === 'invalid_token') { //custom error checking based on the data i get

      console.log('hit error');

      originalRequest._retry = true
      const retryOrigReq = new Promise((resolve, reject) => {
        axios.post(REFRESH_TOKEN_URL, null) //give ur refrsh token url 
          .then((resp) => {
            // console.log(resp)
            self.setState({
              token: resp.data.access_token
            });
            try {
              AsyncStorage.setItem('AUTH_TOKEN', 'bearer ' + resp.data.access_token);
            } catch (error) {
              // Error saving data
            }
            try {
              AsyncStorage.setItem('REFRESH_TOKEN', resp.data.refresh_token);
            } catch (error) {
              // Error saving data
            }
            originalRequest.headers['Authorization'] = 'Bearer ' + resp.data.access_token
            resolve(axios(originalRequest));
          })
          .catch((error) => {
            console.log(error);
          })
      });
      return retryOrigReq;
    } else {
      return Promise.reject(error);
    }
  });
}