umi-request全局攔截

使用umi框架是,網(wǎng)絡(luò)請求用自帶的request進行二次封裝,核心代碼如下。直接放在src下的app.js中即可

const codeMessage = {
  200: '服務(wù)器成功返回請求的數(shù)據(jù)。',
  201: '新建或修改數(shù)據(jù)成功。',
  202: '一個請求已經(jīng)進入后臺排隊(異步任務(wù))。',
  204: '刪除數(shù)據(jù)成功。',
  400: '發(fā)出的請求有錯誤,服務(wù)器沒有進行新建或修改數(shù)據(jù)的操作。',
  401: '用戶沒有權(quán)限(令牌、用戶名、密碼錯誤)。',
  403: '用戶得到授權(quán),但是訪問是被禁止的。',
  404: '發(fā)出的請求針對的是不存在的記錄,服務(wù)器沒有進行操作。',
  405: '請求方法不被允許。',
  406: '請求的格式不可得。',
  410: '請求的資源被永久刪除,且不會再得到的。',
  422: '當創(chuàng)建一個對象時,發(fā)生一個驗證錯誤。',
  500: '服務(wù)器發(fā)生錯誤,請檢查服務(wù)器。',
  502: '網(wǎng)關(guān)錯誤。',
  503: '服務(wù)不可用,服務(wù)器暫時過載或維護。',
  504: '網(wǎng)關(guān)超時。',
};

// 全局請求
const requestInterceptor = (url, options) => {
  return {
    url: 'http://localhost:3009' + url, // 此處可以添加域名前綴
    options: {
      ...options,
      headers: {
        authorization: 'Bearer',
      },
    },
  };
};

// 全局相應(yīng)攔截
const responseInterceptor = (response, options) => {
  console.log('返回了');
  return response;
};

const errorHandler = (error) => {
  const { response } = error;
  if (response && response.status) {
    const errorText = codeMessage[response.status] || response.statusText;
    const { status, url } = response;
    console.log(`請求錯誤 ${status}: ${url}`);
    // notification.error({
    //   message: `請求錯誤 ${status}: ${url}`,
    //   description: errorText,
    // });
  }

  if (!response) {
    // notification.error({
    //   description: '您的網(wǎng)絡(luò)發(fā)生異常,無法連接服務(wù)器',
    //   message: '網(wǎng)絡(luò)異常',
    // });
  }
  throw error;
};

export const request = {
  timeout: 1000,
  errorConfig: {},
  middlewares: [],
  // 異常處理
  errorHandler,
  requestInterceptors: [requestInterceptor],
  responseInterceptors: [responseInterceptor],
};

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容