1. 程式人生 > 實用技巧 >ant desgin pro 的專案中 請求之封裝

ant desgin pro 的專案中 請求之封裝

/**
 * request 網路請求工具
 * 更詳細的 api 文件: https://github.com/umijs/umi-request
 */
import { extend } from 'umi-request';
import { notification, message } from 'antd';
// import qs from 'qs';
import Constants from '@/constans';
const codeMessage = {
  200: '伺服器成功返回請求的資料。',
  201: '新建或修改資料成功。',
  202: '一個請求已經進入後臺排隊(非同步任務)。',
  204: '刪除資料成功。',
  400: '發出的請求有錯誤,伺服器沒有進行新建或修改資料的操作。',
  401: '使用者沒有許可權(令牌、使用者名稱、密碼錯誤)。',
  403: '使用者得到授權,但是訪問是被禁止的。',
  404: '發出的請求針對的是不存在的記錄,伺服器沒有進行操作。',
  406: '請求的格式不可得。',
  410: '請求的資源被永久刪除,且不會再得到的。',
  422: '當建立一個物件時,發生一個驗證錯誤。',
  500: '伺服器發生錯誤,請檢查伺服器。',
  502: '閘道器錯誤。',
  503: '服務不可用,伺服器暫時過載或維護。',
  504: '閘道器超時。',
};
/**
 * 異常處理程式
 */

const errorHandler = error => {
  const { response } = error;
  if (response && response.status) {
    const errorText = codeMessage[response.status] || response.statusText;
    const { status, url } = response;
    notification.error({
      message: `請求錯誤 ${status}: ${url}`,
      description: errorText,
    });
  } else if (!response) {
    notification.error({
      description: '您的網路發生異常,無法連線伺服器',
      message: '網路異常',
    });
  }

  return response;
};
/**
 * 配置request請求時的預設引數
 */

const request = extend({
  errorHandler,
  // 預設錯誤處理
  credentials: 'include', // 預設請求是否帶上cookie
  // headers: {
  //   'Content-Type': 'application/x-www-form-urlencoded',
  // },
});

// request攔截器
request.interceptors.request.use(async (url, options) => {
  let currentUser = JSON.parse(sessionStorage.getItem('currentUser'));
  let token = sessionStorage.getItem('token');
  if (currentUser) {
    let params = options.params;

    // if (options.data && typeof options.data == 'object') {
    //   options.data = qs.stringify(options.data);
    // }

    params = {
      token: token,
      hotel_id: currentUser.hotel_id,
      hotelId: currentUser.hotel_id,
      hotel_group_id: currentUser.hotel_group_id,
      hotelGroupId: currentUser.hotel_group_id,
      user_id: currentUser.id,
      // modify_user: currentUser.id,
      ...params,
    };

    if ('get' != options.method) {
      params = {
        modify_user: currentUser.id,
        ...params,
      };
    }

    return {
      url: url,
      options: {
        ...options,
        params,
        // params: {
        //   token: token,
        //   hotel_id: currentUser.hotel_id,
        //   hotelId: currentUser.hotel_id,
        //   hotel_group_id: currentUser.hotel_group_id,
        //   hotelGroupId: currentUser.hotel_group_id,
        //   modify_user: currentUser.id,
        //   ...params,
        // },
      },
    };
  }
});

// response攔截器
request.interceptors.response.use(async response => {
  const data = await response.clone().json();
  if (data.code == Constants.UN_LOGIN || data.code == Constants.MORE_THEN_ONE_LOGIN) {
    // 未登入或多點登入
    message.warn(data.message);
    sessionStorage.removeItem('currentUser');
    window.location.href = '/';
  } else if (data.code !== Constants.SUCCESS) {
    if (data.message) {
      message.error(data.message);
    }
    return response;
  } else {
    return response;
  }
});

export default request;