How do I create configuration for axios for default request headers in every http call?

前端 未结 3 1640
你的背包
你的背包 2020-12-13 15:51

https://github.com/MrFiniOrg/AxiosQuestion

I would like to have my project setup so that I do not have to specify the same request header in every http call.

3条回答
  •  既然无缘
    2020-12-13 16:39

    Using interceptors, it runs on each request so if the token changes (refreshes) then the next request picks up the new token. Check for existing values in the request to allow overriding of the header. Consider we are using any token generator and updating token in local storage. Here we are using keyclock object that is stored in localStorage

    import * as axios from "axios";
    axios.defaults.baseURL = process.env.REACT_APP_BASE_URL;
    
    axios.interceptors.request.use(
      config => {
        if (!config.headers.Authorization) {
          const token = JSON.parse(localStorage.getItem("keyCloak")).token;
    
          if (token) {
            config.headers.Authorization = `Bearer ${token}`;
          }
        }
    
        return config;
      },
      error => Promise.reject(error)
    );
    

提交回复
热议问题