1

我有这个目录结构:

//app
    //public
        //index.html
        //assets
        //favicon.ico
    //src
        //components
        //App.js
        //index.js

在哪里放置interceptor?我应该使用服务创建一个单独的目录并将其导入文件App.js吗?

拦截器

axios.defaults.baseURL = localStorage.getItem('domain');

let isRefreshing = false;
let failedQueue = [];

const processQueue = (error, token = null) => {
  failedQueue.forEach(prom => {
    if (error) {
      prom.reject(error);
    } else {
      prom.resolve(token);
    }
  }) 
  failedQueue = [];
}

axios.interceptors.response.use(function (response) {
  document.body.classList.remove('loading-indicator');

  return response;
}, error => {

  const originalRequest = error.config;

  if (error.response.status === 401 && !originalRequest._retry) {     
    if (isRefreshing) {
      return new Promise((resolve, reject) => {
        failedQueue.push({resolve, reject})
      }).then(token => {
        originalRequest.headers["Authorization"] = "Bearer " + token;
        return axios(originalRequest);
      }).catch(err => {
        return Promise.reject(err);
      })
    }

    originalRequest._retry = true;
    isRefreshing = true;

    const data = qs.stringify({
      grant_type: "refresh_token",
      client_id: "****",
      client_secret: "******",
      refresh_token: window.localStorage.getItem("token")
    const config = {
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      }
    }

    return new Promise(function (resolve, reject) {
      axios({ 
        method: "post", 
        url: "/oauth2/token", 
        data, 
        config
      }) 
      .then(({data}) => {
        const token = data;

      })
      .catch((err) => {
        processQueue(err, null);
        reject(err);
      })
      .then(() => { isRefreshing = false })
    })
  }

  return Promise.reject(error);
});
4

0 回答 0