Using axios in react, how to get the token returned by login interface?

here"s the thing!

the project uses react + axios , and token needs to be set in header for axios to send requests.

The problem with

is that token is returned from the login api interface. So obviously, this token is worth saving as a global variable. This token is needed because the axios sending interface is also used in other components.

  1. is stored in localstorage and read from localstorage every time a request is sent.
  2. Storage with redux

want to ask three questions:

  1. will there be performance problems in mode 1? after all, localstorage is different from ordinary functions
  2. Mode 2, if the project itself does not use redux, it seems to be a bit overqualified, which is strange.
  3. is there another way? how do you deal with it?

set token directly to the default request header, which is automatically carried with each request.

import axios from 'axios';

const TOKEN_KEY = 'AS_MALL_ACCESS_TOKEN';

axios.defaults.headers.common['Authorization'] = localStorage.getItem(TOKEN_KEY);

when token is updated, localStorage re-caches axios.defaults.headers.common updates.


generally speaking, you need to use localstorage and window (global) together.
first of all, you can get the token, from the background and assign the token to the window, that is, this, so that you can use this.token, anywhere. But once the user closes the browser, the js execution environment disappears, and the second time you open the browser, you need to log in again to obtain the token,. Obviously, this is not what we want to save the login information, so the correct step is:
1, after the login is successful, This.token = res.data.token, also stores token in localstorage, so that every request uses this.token, instead of going to localstorage to fetch
2. When the user closes the browser, the next time he enters, he takes localstorage, and assigns the result to this, that is, this.token = the token you got
3. The token in remove localstorage

only when the user logs out.
Menu