/**
* 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;