react ant design項目,使用umi-request實現http緩存

//'useCache'當'useCache'爲true時,GET請求將在ttl毫秒內緩存。
  //緩存鍵爲“ url +參數+方法”。
  useCache:false//默認

  //'ttl'緩存持續時間(毫秒),0爲無窮大
  ttl:60000//'maxCache'是要緩存的最大請求數,0表示無窮大。
  maxCache:0// 根據http協議,GET請求用於從服務器獲取數據,當服務器數據更新不頻繁時,有必要緩存響應數據。
  // 對於某些需要使用其他方法要求緩存數據的情況,
  validateCache: (url, options) => { return options.method.toLowerCase() === 'get' },

github地址

import {extend} from 'umi-request';

/**
 * 配置request請求時的默認參數
 */
const request = extend({
  errorHandler, // 默認錯誤處理
  // credentials: 'include', // 默認請求是否帶上cookie
  prefix: '/rest', //前綴
});

/**
 * request攔截器, 改變url 或 options.
 */
request.interceptors.request.use((url: string, options: any) => {
  const token = localStorage.getItem('auth');
  const headers = {
    Accept: 'application/json',
    Authorization: '',
  };
  if (token) {
    headers.Authorization = token;
    return {
      url: `${basicUrl}${url}`,
      options: {
        interceptors: true,
        headers,
        useCache: true,
        ttl: 60000,
        maxCache: 0,
        timeout:5000,
        ...options,
      },
    };
  }
  return {
    url: `${basicUrl}${url}`,
    options: {...options, interceptors: true,},
  };
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章