Attach Authorization header for all axios requests

前端 未结 9 2007
灰色年华
灰色年华 2020-12-04 05:17

I have a react/redux application that fetches a token from an api server. After the user authenticates I\'d like to make all axios requests have that token as an Authorizati

9条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 05:24

    export const authHandler = (config) => {
      const authRegex = /^\/apiregex/;
    
      if (!authRegex.test(config.url)) {
        return store.fetchToken().then((token) => {
          Object.assign(config.headers.common, { Authorization: `Bearer ${token}` });
          return Promise.resolve(config);
        });
      }
      return Promise.resolve(config);
    };
    
    axios.interceptors.request.use(authHandler);
    

    Ran into some gotchas when trying to implement something similar and based on these answers this is what I came up with. The problems I was experiencing were:

    1. If using axios for the request to get a token in your store, you need to detect the path before adding the header. If you don't, it will try to add the header to that call as well and get into a circular path issue. The inverse of adding regex to detect the other calls would also work
    2. If the store is returning a promise, you need to return the call to the store to resolve the promise in the authHandler function. Async/Await functionality would make this easier/more obvious
    3. If the call for the auth token fails or is the call to get the token, you still want to resolve a promise with the config

提交回复
热议问题