A
A
ar52018-04-03 17:55:10
JavaScript
ar5, 2018-04-03 17:55:10

How to properly use spoilers in axios?

Hello, I wanted to learn from more experienced colleagues how to use interceptors correctly both when requesting and when responding. Is it possible to control routing on requests?

axios.interceptors.request.use(
  function(config) {
    if (!config.url.includes('Authenticate') && !config.headers.common['X-RANDOMIZE-TOKEN']) {
      const token = localStorage.getItem('token');
      if (token) {
        config.headers.common['X-RANDOMIZE-TOKEN'] = token;
        axios.defaults.headers.common['X-RANDOMIZE-TOKEN'] = token;
      } else {
        router.replace('/login');
        return config;
      }
    }
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  response => {
    return response;
  },
  function(error) {
    EventBus.$emit('error-notify', error);
    if (error.response.status === 401) {
      router.replace('/login');
    }
    return Promise.reject(error.response);
  }
);

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Markin, 2018-04-04
@owl1n

I will show a few practices, how spoilers make life easier for me, and for many, in general.
Here and below, I will show exactly the use of interceptors when working with JWT authorization (tokens).
1) Authorization header substitution

const createSetAuthInterceptor = options => config => {
  if (options.access) {
    config.headers.Authorization = options.access;
  } else {
    delete config.headers.Authorization;
  }
  return config;
};

const setAuthCb = createSetAuthInterceptor(store.state.auth);
axios.interceptors.request.use(setAuthCb);

Here we check the availability of access from the store, or rather, the presence of a token. Next, substitute or delete the title.
2) The next practice is to refresh the token (what you asked about in the comment, at the end of the session, etc.)
let refreshTokenPromise;

const createUpdateAuthInterceptor = (store, http) => async error => {
  const message = get(error, 'response.data.message');
  if (!['Token expired', 'Invalid token'].includes(message)) {
    return Promise.reject(error);
  }

  if (!refreshTokenPromise) {
    refreshTokenPromise = store.dispatch('refreshToken');
  }

  await refreshTokenPromise;
  refreshTokenPromise = null;

  return http(error.config);
};

const updateAuthCb = createUpdateAuthInterceptor(store, axios);
axios.interceptors.response.use(null, updateAuthCb);

Here we can see that with each response we check for errors and if the error corresponds to an error with a token, then we send to update the token and then we send the same request that returned to us with an error again. Here, not the error message itself will be correctly checked, but the response code (401, etc.), but here such a solution is used already because of the specifics of the back.
In the same solution, instead of updating the token, you can send the user to log in himself, to the authorization page. To do this, of course, it is worth passing not a store instance, but a router instance in order to redirect the user. I hope it helped and at least somehow clearly showed how to use it :)

E
Evgeny Kulakov, 2018-04-04
@kulakoff Vue.js

It is possible - this is one of the practices, i.e. when you make a request to the api for the first time, for example, to get the current user, and in case you get an access error, go to the authorization page.
But you can also implement similar behavior using the view router hooks. Those. in the .beforeEach hook, you make a user request if you immediately switch to authorization in the exception:

store.dispatch('urrent_user')
        .then(r => {
            // next processing
        })
        .catch(e => {
             // goto login
        })

A
Artem0071, 2018-04-03
@Artem0071

In general, interceptors for another
. For example, you can turn on the loading indicator on the "download start event", and turn it off on the "download end event"
And what about the connection between routing and Ajax, there are hooks in the view . Here in them you can process data when page transitions occur

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question