E
E
Egor Astreiko2020-11-12 20:30:44
Vue.js
Egor Astreiko, 2020-11-12 20:30:44

How to do an additional one before the main request?

Hello everyone, tell me how to specify in the axios nuxt.js settings, so that before any request to the server, axios checks whether the access token has expired, if so, then before the main request it made a request to update the token and after a successful update of the token, it already passed to the main request?

What I mean:
Let's say the access token lives for 5 minutes, the user is authenticated, his access token and lifetime are recorded in the cookie, refsresh in localStorage, and the data in store. He didn’t do anything for 6 minutes, the access token lifetime has expired, he refreshes the page, there is no data in the store, a request is made to get his data, the server sends a 401 error and this error is visible in the console. And I want that before requesting user data, if there is an access token and its lifetime, axios checks whether the lifetime has expired, if so, it immediately updated the token, and after a successful update it already knocked on the address to get user data.

I would also like to know if this is the right approach and is it worth doing this at all?
If yes, then I would like to know more information on how to implement this.
If not, why is it bad and how to do it better.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Aetae, 2020-11-12
@Egor1324

This is the usual way.

axios.interceptors.request.use(async config => {
  const token = await getToken(); // тут либо отдаём живой токен сразу, либо получаем новый
  config.headers.Authorization = 'Bearer ' + token;
  return config;
});
You don't have to wait for mistakes.
But in general, nuxt has its own auth module , where everything is already thought out and provided in advance, so it’s better to use it.

A
Alexey Yarkov, 2020-11-12
@yarkov Vue.js

Normal way. It is necessary to respond to a 401 error and execute a request for a new token, and then repeat the desired request.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question