Я хочу, когда я получил код ошибки 401, то приложение выйдет из системы. Но в моем случае, выйти из API-вызова, но это не выход из системы должным образом - PullRequest
1 голос
/ 10 октября 2019
const store = configureStore();
let isLogout = false;
const handleResponse = (response) => {
  if (response && response.data && response.data.status && response.data.status.code === 401 && !isLogout ) {
    isLogout = true;
    store.getState().Login.isAuthenticated= false;
    store.dispatch(actions.logout());
  }
  return response
}

axiosApi.interceptors.response.use(
  response => handleResponse(response)
)
``` 
const initial_state = {
  userName: 'Name',
  isAuthenticated: localStorage.getItem('isAuthenticated') ? true : false
};

export default function loginReducers (state, action) {
  if (typeof state === 'undefined') {
    return initial_state;
  }
  const payload = action.payload || action;
  switch (action.type) {
    case loginConstants.LOGOUT_SUCCESS:
      return {
        initial_state,
        isAuthenticated: false
      };
    case loginConstants.SET_IS_AUTHENTICATED:
      return {
        isAuthenticated: payload.isAuthenticated
      };
    default:
      return state;
  }
}
```

Я упомянул свое действие при входе в систему, а также редуктор входа в систему.

   const userObj = JSON.parse(localStorage.getItem('authResponse'))
   const userId = 'abcd'
   const config = {};
   config.url = 'abc/logout?userId=' + userId;
   config.headers = {
     'Accept': 'application/json',
     'Content-Type': 'application/json'
   };
   dispatch(blockUI());

   ApiCall.getCall(config).then((response) => {
     if (response && response.status) {
       if ((response.status.code === 200 || response.status.code === 201)) {
         history.push('/login');
         localStorage.clear();
         dispatch({ type: LoginConstants.LOGOUT_SUCCESS });

       }
     }
     dispatch(unblockUI());
   });
 })

Я упомянул свое действие при входе в систему, также редуктор входа в систему. Как изменить состояние избыточности с помощью store.getstate (). Я хочу, когда я получил код ошибки 401, то приложение выйдет из системы. Но в моем случае, выйти из API-вызова, но это не выход из системы

1 Ответ

0 голосов
/ 10 октября 2019

В axios docs он имеет эту информацию, поэтому вам нужно обработать вторую часть для ошибок, отличных от 2xx, в вашем случае 401.

axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

Предполагая ваш код 401 в error.status.code:

axiosApi.interceptors.response.use(
    function(response) {
      return response;
    },
    function(error) {
       if (error.status.code === 401 ) {
        store.dispatch(actions.logout());
      }

      return Promise.reject(error);
    }
  );

Если вы используете токен, при выходе из системы вам лучше удалить его.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...