提交 503b157d authored 作者: 钟是志's avatar 钟是志

bug修改

上级 a979f0f3
// use localStorage to store the authority info, which might be sent from server in actual project.
export function getAuthority(str) {
// return localStorage.getItem('antd-pro-authority') || ['admin', 'user'];
const authorityString =
typeof str === 'undefined' ? localStorage.getItem('antd-pro-authority') : str;
// authorityString could be admin, "admin", ["admin"]
let authority;
try {
authority = JSON.parse(authorityString);
} catch (e) {
authority = authorityString;
}
if (typeof authority === 'string') {
return [authority];
}
return authority || ['admin'];
}
export function setAuthority(authority) {
const proAuthority = typeof authority === 'string' ? [authority] : authority;
return localStorage.setItem('antd-pro-authority', JSON.stringify(proAuthority));
}
export function setActiveMenus(menuTree) {
return localStorage.setItem('antd-pro-menuTree', JSON.stringify(menuTree));
}
export function getActiveMenus(){
let info = localStorage.getItem('antd-pro-menuTree');
try {
info = JSON.parse(info);
} catch(e) {
info = [];
}
if(!info){
info = [];
}
return info;
}
export function setIconConfig(config) {
return localStorage.setItem('icon-appIcon-config', JSON.stringify(config));
}
export function getIconConfig(){
return JSON.parse(localStorage.getItem('icon-appIcon-config'));
}
export function setToken(token) {
return localStorage.setItem('antd-pro-token', token);
}
export function getToken() {
return localStorage.getItem('antd-pro-token');
}
export function setSysConfig(data) {
return localStorage.setItem('xg-web-sysconfig', JSON.stringify(data));
}
export function getSysConfig() {
const sysConfig = localStorage.getItem('xg-web-sysconfig');
if (sysConfig) {
return JSON.parse(sysConfig);
}
return {};
}
export function setFetchUrl(data) {
return localStorage.setItem('fetch-url-data', data);
}
export function getFetchUrl() {
return localStorage.getItem('fetch-url-data');
}
export function setAllArea(data) {
return localStorage.setItem('antd-pro-area-all', data);
}
export function getAllArea() {
return localStorage.getItem('antd-pro-area-all');
}
export function setType(type) {
return localStorage.setItem('antd-pro-type', type);
}
export function getType() {
return localStorage.getItem('antd-pro-type')||"";
}
export function setSignUperToken(token) {
return localStorage.setItem('antd-pro-signUperToken', token);
}
export function getSignUperToken() {
return localStorage.getItem('antd-pro-signUperToken');
}
function isObject (value) {
return value === Object(value)
}
function isArray (value) {
return Array.isArray(value)
}
function isFile (value) {
return value instanceof File
}
function makeArrayKey (key) {
return key
}
function objectToFormData (obj, fd, pre) {
fd = fd || new FormData()
Object.keys(obj).forEach(function (prop) {
var key = pre ? (pre + '[' + prop + ']') : prop
if (isObject(obj[prop]) && !isArray(obj[prop]) && !isFile(obj[prop])) {
objectToFormData(obj[prop], fd, key)
} else if (isArray(obj[prop])) {
obj[prop].forEach(function (value) {
var arrayKey = makeArrayKey(key)
if (isObject(value) && !isFile(value)) {
objectToFormData(value, fd, arrayKey)
} else {
fd.append(arrayKey, value)
}
})
} else {
if(obj[prop]!=null) fd.append(key, obj[prop])
}
})
return fd
}
export default objectToFormData
import { fetch } from 'dva';
import { notification, Icon } from 'antd';
import router from 'umi/router';
import FormdataWrapper from './object-to-formdata-custom';
import { getToken, setToken } from './authority';
import config from 'config';
let messageTime = new Date().getTime() - 3000 ;
const controlNotification = (props) => {
let nowTime = new Date().getTime();
if(nowTime - messageTime < 3000){
return ;
}
messageTime = nowTime;
notification.info({
...props,
icon:
<Icon type="info-circle"
style={{color: '#fa8c16'}}
/>
});
return true;
};
const codeMessage = {
200: '服务器成功返回请求的数据。',
201: '新建或修改数据成功。',
202: '一个请求已经进入后台排队(异步任务)。',
204: '删除数据成功。',
400: '发出的请求有错误,服务器没有进行新建或修改数据的操作。',
401: '登录已过期,请重新登录',
403: '用户得到授权,但是访问是被禁止的。',
404: '发出的请求针对的是不存在的记录,服务器没有进行操作。',
406: '请求的格式不可得。',
410: '请求的资源被永久删除,且不会再得到的。',
422: '当创建一个对象时,发生一个验证错误。',
500: '服务器发生错误,请检查服务器。',
502: '网关错误。',
503: '服务不可用,服务器暂时过载或维护。',
504: '网关超时。',
};
const checkStatus = response => {
if (response.status !== 401) {
return response;
}
const errortext = codeMessage[response.status] || response.statusText;
const token = getToken();
if (token && token !== 'null') {
controlNotification({
message: `${response.status === 401 ? '登录过期' : '请求错误'}`,
description: errortext,
});
}
if (response.status === 401) {
setToken(null);
}
const error = new Error(errortext);
error.name = response.status;
error.response = response;
throw error;
};
/**
* Requests a URL, returning a promise.
*
* @param {string} url The URL we want to request
* @param {object} [options] The options we want to pass to "fetch"
* @return {object} An object containing either "data" or "err"
*/
export default function request(
url,
options = {},
) {
let defaultToken = getToken();
const token = defaultToken !== null && defaultToken !== 'null' ? defaultToken : '';
/**
* Produce fingerprints based on url and parameters
* Maybe url has the same parameters
*/
if (token) {
url = url + '?token=' + token;
}
const defaultOptions = {
credentials: 'omit',
mode: 'cors',
};
const newOptions = { ...defaultOptions, ...options };
if (newOptions.method === 'POST' ||
newOptions.method === 'PUT' ||
newOptions.method === 'DELETE') {
if (!(newOptions.body instanceof FormData)) {
newOptions.headers = {
Accept: 'application/json',
...newOptions.headers,
};
newOptions.body = FormdataWrapper(newOptions.body);
} else {
// newOptions.body is FormData
newOptions.headers = {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
...newOptions.headers,
};
}
}
return fetch(url, newOptions)
.then(checkStatus)
.then(response => {
if (response.status !== 200) {
return response.text();
}
return response.json();
})
.then(response => {
if (typeof response == 'string') {
try {
const xxx = JSON.parse(response);
if (xxx.errMsg) {
controlNotification({
//message: '',
message: xxx.errMsg,
});
return null;
}
return xxx;
} catch (e) {
return response;
}
}
return response;
})
.catch(e => {
const status = e.name;
if (status === 401) {
if(window.top != window.self){
window.top.postMessage("returnLogin", '*'); // Iframe 返回登录页
return true;
}
// @HACK
/* eslint-disable no-underscore-dangle */
window.g_app._store.dispatch({
type: 'login/logout',
});
return false;
}
// environment should not be used
if (status === 403) {
router.push('/exception/403');
return false;
}
if (status <= 504 && status >= 500) {
router.push('/exception/500');
return false;
}
if (status >= 404 && status < 422) {
router.push('/exception/404');
}
let systemName = '';
if(!window.navigator.onLine){
return controlNotification({
message: '网络故障',
description: `${systemName}无法连接到网络,请稍后再试`,
});
}
controlNotification({
message: '网络故障',
description: `${systemName}无法连接到服务器,请稍后再试`,
});
return;
});
}
/*
* 下载文件
* @params { String, String} [下载地址, 下载文件名]
* */
export function download(url, filename){
return new Promise(function(resolves) {
getBlob(url).then(function(blob) {
saveAs(blob, filename);
resolves(`success`)
});
function getBlob(url) {
return new Promise(function(resolve) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function() {
if(xhr.status === 200) {resolve(xhr.response)}
};
xhr.send();
});
}
function saveAs(blob, filename) {
if(window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename);
} else {
const link = document.createElement('a');
const body = document.querySelector('body');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.style.display = 'none';
body.appendChild(link);
link.click();
body.removeChild(link);
window.URL.revokeObjectURL(link.href);
}
}
})
}
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论