feat: requst utils done

pull/1461/head
yikai 2 years ago
parent 26abb9092c
commit 693e918886

@ -1,5 +1,3 @@
const { off } = require("process");
module.exports = {
env: {
browser: true,

@ -8,8 +8,8 @@
"@testing-library/user-event": "^13.5.0",
"ahooks": "^3.7.8",
"antd": "^5.4.7",
"axios": "^1.5.0",
"i18next": "^23.5.1",
"qs": "^6.11.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-i18next": "^13.2.2",

@ -1,127 +0,0 @@
import request from '../axios/request';
export function userLogin(data) {
return request('post', '/hippo4j/v1/cs/auth/login', data);
}
export function getInfo() {
return request('get', '/hippo4j/v1/cs/user/info');
}
export function logout() {
return request('post', '/hippo4j/v1/cs/user/logout');
}
function islogin({ commit }, userInfo) {
const { username, password } = userInfo;
return new Promise((resolve, reject) => {
let key = genKey();
let encodePassword = encrypt(password, key);
key = key.split('').reverse().join('');
login({ username: username.trim(), password: encodePassword, tag: key, rememberMe: 1 })
.then(response => {
const { data } = response;
const { roles } = response;
commit('SET_TOKEN', data);
localStorage.setItem('roles', JSON.stringify(roles));
localStorage.setItem('USER_ROLE', roles[0]);
setToken(data);
resolve();
})
.catch(error => {
// alert('登录失败')
reject(error);
});
});
}
// get user info
function getInfo({ commit, state }) {
return new Promise((resolve, reject) => {
const data = {};
data.roles = JSON.parse(localStorage.getItem('roles'));
commit('SET_ROLES', data.roles);
resolve(data);
});
}
// user logout
function logout({ commit, state }) {
// return new Promise((resolve, reject) => {
// logout(state.token).then(() => {
// commit('SET_TOKEN', '')
// commit('SET_ROLES', [])
// removeToken()
// resetRouter()
// resolve()
// }).catch(error => {
// reject(error)
// })
// })
return new Promise(resolve => {
commit('SET_TOKEN', '');
commit('SET_ROLES', []);
removeToken();
resetRouter();
resolve();
});
}
// remove token
function resetToken({ commit }) {
return new Promise(resolve => {
commit('SET_TOKEN', '');
commit('SET_ROLES', []);
removeToken();
resolve();
});
}
// dynamically modify permissions
function changeRoles({ commit, dispatch }, role) {
return new Promise(async resolve => {
const token = role + '-token';
commit('SET_TOKEN', token);
setToken(token);
const { roles } = await dispatch('getInfo');
resetRouter();
// generate accessible routes map based on roles
const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true });
// dynamically add accessible routes
router.addRoutes(accessRoutes);
// reset visited views and cached views
dispatch('tagsView/delAllViews', null, { root: true });
resolve();
});
}
const mutations = {
SET_TOKEN: (state, token) => {
state.token = token;
},
SET_INTRODUCTION: (state, introduction) => {
state.introduction = introduction;
},
SET_NAME: (state, name) => {
state.name = name;
},
SET_AVATAR: (state, avatar) => {
state.avatar = avatar;
},
SET_ROLES: (state, roles) => {
state.roles = roles;
},
};
export default {
userLogin,
getInfo,
logout,
};

@ -1,4 +0,0 @@
const devBaseUrl = 'http://console.hippo4j.cn:6691/hippo4j/v1/cs';
const proBaseUrl = 'http://console.hippo4j.cn:6691/hippo4j/v1/cs';
export const BASE_URL = process.env.NODE_ENV === 'development' ? devBaseUrl : proBaseUrl;
export const TIMEOUT = 5000;

@ -1,201 +0,0 @@
import axios from 'axios';
import { BASE_URL, TIMEOUT } from './config';
const instance = axios.create({
baseURL: BASE_URL,
timeout: TIMEOUT,
});
instance.interceptors.request.use(
config => {
config.data = JSON.stringify(config.data);
config.headers = {
'Content-Type': 'application/json',
};
return config;
},
err => {
return Promise.reject(err);
}
);
instance.interceptors.response.use(
res => {
if (res.code === 'A000004') {
removeToken();
resetRouter();
alert(res.message);
document.location.href = 'index.html';
} else if (res.code !== '20000' && res.code !== '0' && res.code !== '200') {
Message({
message: res.message || 'Error',
type: 'error',
duration: 5 * 1000,
});
// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
if (res.code === '50008' || res.code === '50012' || res.code === '50014') {
// to re-login
MessageBox.confirm(
'You have been logged out, you can cancel to stay on this page, or log in again',
'Confirm logout',
{
confirmButtonText: 'Re-Login',
cancelButtonText: 'Cancel',
type: 'warning',
}
).then(() => {
store.dispatch('user/resetToken').then(() => {
location.reload();
});
});
}
console.log(res);
return Promise.reject(new Error(res.message || 'Error'));
} else {
const { data } = response;
const { code } = data;
// 状态码为0||200表示api成功
if (code === '0') {
const { data: res } = data;
return res;
} else if (code === '200') {
return data;
} else {
// 返回数据
return res;
}
}
return response;
},
err => {
console.log('err' + err); // for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000,
});
return Promise.reject(err);
}
);
/**
* 封装get
* @param {String} url
* @param {String} param
* @returns
*/
export function get(url, param = {}) {
return new Promise((resolve, reject) => {
axios
.get(url, {
params: param,
})
.then(response => {
console.log('get error: url, params, state', url, params, response.data);
resolve(response.data);
})
.catch(err => {
msg(err);
reject(err);
});
});
}
/**
*
* 封装post
* @param {String} url
* @param {Object} param
* @returns {Promise}
*/
export function post(url, param) {
return new Promise((resolve, reject) => {
axios.post(url, param).then(
response => {
resolve(response.data);
},
err => {
reject(err);
}
);
});
}
export default function (fecth, url, param) {
return new Promise((resolve, reject) => {
switch (fecth) {
case 'get':
console.log('a get request, url:', url);
get(url, param)
.then(response => {
resolve(response);
})
.catch(err => {
console.log('GET request error, err:', err);
reject(err);
});
break;
case 'post':
post(url, param)
.then(response => {
resolve(response);
})
.catch(err => {
console.log('POST request error, err:', err);
reject(err);
});
break;
default:
break;
}
});
}
function msg(err) {
if (err && err.response) {
switch (err.response.status) {
case 400:
alert(err.response.data.error.details);
break;
case 401:
alert('未授权,请登录');
break;
case 403:
alert('拒绝访问');
break;
case 404:
alert('请求地址出错');
break;
case 408:
alert('请求超时');
break;
case 500:
alert('服务器内部错误');
break;
case 501:
alert('服务未实现');
break;
case 502:
alert('网关错误');
break;
case 503:
alert('服务不可用');
break;
case 504:
alert('网关超时');
break;
case 505:
alert('HTTP版本不受支持');
break;
default:
}
}
}

@ -0,0 +1,18 @@
import React, { createContext, useState, ReactNode } from 'react';
export enum THEME_NAME {
DEFAULT = 'default',
DARK = 'dark',
}
export const StoreContext = createContext<{
themeName: string;
setThemeName: (name: THEME_NAME) => void;
} | null>(null);
export const Store: React.FC<{
children: ReactNode;
}> = ({ children }) => {
const [themeName, setThemeName] = useState<string>(THEME_NAME.DEFAULT);
return <StoreContext.Provider value={{ themeName, setThemeName }}>{children}</StoreContext.Provider>;
};

@ -0,0 +1,6 @@
import React from 'react';
const HomeDetail = () => {
return <></>;
};
export default HomeDetail;

@ -1,8 +1,17 @@
import { Button, Card } from 'antd';
import { Button } from 'antd';
import request from '@/utils';
const Home = () => {
const fetchdata = (body: { duid: string }) => {
return request<{ phone: string }>('https://mock.xiaojukeji.com/mock/16635/am/marketing/mis/member/archive/phone', {
method: 'post',
body,
});
};
return (
<div style={{ color: 'red' }}>
<Button>jjjjj</Button>
<Button onClick={() => fetchdata({ duid: '1234234' })}>jjjjj</Button>
</div>
);
};

@ -0,0 +1,9 @@
const fetchData = async () => {
await new Promise(resolve => {
resolve(100);
});
};
const service = { fetchData };
export default service;

@ -0,0 +1,3 @@
export enum CON {
NAME = '1',
}

@ -1,81 +1,6 @@
import { Form, Input, Button } from 'antd'
import userLogin from '../../API/user'
import React from 'react';
const Login = (props: any) => {
const data = {
passwordType: 'password',
capsTooltip: false,
loading: false,
showDialog: false,
redirect: undefined,
otherQuery: {},
loginForm: {
username: '',
password: '',
},
// loginRules: {
// // username: [{ required: true, trigger: 'blur', validator: validateUsername }],
// // password: [{ required: true, trigger: 'blur', validator: this.validatePassword }],
// },
};
const validatePassword = (_: any, value: any) => {
if (value.length < 6) {
return Promise.reject(new Error('The password can not be less than 6 digits'))
} else if (value.length > 72) {
return Promise.reject(new Error('The password can not be greater than 72 digits'))
}
return Promise.resolve()
};
const [form] = Form.useForm()
const onFinish = () => {
let loginParams = {
username: form.getFieldValue('username'),
password: form.getFieldValue('password'),
// username: 'baoxinyi_admin',
// password: 'baoxinyi_admin',
rememberMe: 1,
}
data.loginForm.username = form.getFieldValue('username')
console.log('loginParams: ', loginParams)
data.loading = true
userLogin(loginParams)
.then((resolve: any) => {
console.log(resolve)
//登录成功后将当前登录用户写入cookie
// this.$cookie.set('userName', this.loginForm.username)
// console.log('success submit.')
// this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
data.loading = false
})
.catch((e: any) => {
console.log('login error.',e)
data.loading = false
})
};
return (
<div className="login-container">
<Form name="loginForm" form={form} onFinish={onFinish} style={{ maxWidth: 600 }}>
<div className="title-container">
<h3 className="title"></h3>
{/* <h3 className="title">{{ $t('system.login') }}</h3> */}
</div>
<Form.Item name="username" label="用户名" rules={[{ required: true, message: 'Username is required' }]}>
<Input placeholder="用户名" />
</Form.Item>
<Form.Item name="password" label="密码" rules={[{validator: validatePassword}, {required: true, message: 'Street is required'}]}>
<Input placeholder="密码" />
</Form.Item>
<Form.Item name="submit">
<Button type="primary" htmlType="submit" className="login-button">
</Button>
</Form.Item>
</Form>
</div>
);
const Login = () => {
return <></>;
};
export default Login;
export default Login;

@ -1,12 +0,0 @@
const proxy = require('http-proxy-middleware');
module.exports = function (app) {
app.use(
proxy.createProxyMiddleware('/hippo4j/v1/cs', {
target: 'http://console.hippo4j.cn:6691/hippo4j/v1/cs',
changeOrigin: true,
secure: false,
pathRewrite: { '^/hippo4j/v1/cs': '' },
})
);
};

@ -1,11 +0,0 @@
import { createStore} from 'redux';
import reducer from './reducer'
const initState = { money: 0 };
const store = createStore(
reducer,
initState,
);
export default store;

@ -0,0 +1,11 @@
// is plain object
const isPlainObject = (obj: { [key: string]: any }): boolean => {
let proto, Ctor;
if (!obj || typeof obj !== 'object') return false;
proto = Object.getPrototypeOf(obj);
if (!proto) return true;
Ctor = Object.prototype.hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return typeof Ctor === 'function' && Ctor === Object; // insure is new by Object or {}
};
export { isPlainObject };

@ -0,0 +1,3 @@
import request from './request';
export * from './common';
export default request;

@ -0,0 +1,159 @@
import { isPlainObject } from '../common';
import { notification, message } from 'antd';
import Qs from 'qs';
type HttpMethods = 'POST' | 'post' | 'GET' | 'get' | 'DELETE' | 'delete' | 'PUT' | 'put';
interface HeaderConfig extends Record<string, any> {
Accept?: string;
'Content-Type'?: string;
}
interface RequestOptions {
headers?: HeaderConfig;
method?: HttpMethods;
params?: { [key: string]: string } | null;
body?: { [key: string]: string } | null;
timeout?: number;
credentials?: boolean;
moda?: 'cors' | 'same-origin';
cache?: 'no-cache' | 'default' | 'force-cache';
customize?: boolean;
responseType?: 'TEXT' | 'JSON' | 'BLOB' | 'ARRAYBUFFER';
}
type Response<T = any> = {
success: boolean;
data?: T;
module?: T;
msg?: string;
status?: number;
message?: string;
code?: string | number;
};
let baseURL = 'http://127.0.0.1:9999';
const inital: RequestOptions = {
method: 'GET',
params: null,
body: null,
headers: {
'Content-Type': 'application/json',
},
credentials: true,
responseType: 'JSON',
cache: 'no-cache',
};
const env = process.env.NODE_ENV || 'development';
enum IENV_ENUM {
DEVELOPMENT = 'development',
TEST = 'test',
PRODUCTION = 'production',
}
switch (env) {
case IENV_ENUM.DEVELOPMENT:
baseURL = '';
break;
case IENV_ENUM.TEST:
baseURL = '';
break;
case IENV_ENUM.PRODUCTION:
baseURL = '';
break;
}
const codeMessage: { [key: string]: string } = {
'200': '请求已成功被服务器处理,并返回了请求的内容。',
'201': '请求已成功,并且服务器创建了一个新的资源作为响应。',
'202': '一个请求已进入后台排队',
'204': '请求已成功处理,但响应中没有返回任何内容。',
'400': '客户端发送的请求有错误,服务器无法处理。',
'401': '客户端需要提供有效的身份验证信息,以便访问受保护的资源。',
'403': '服务器理解了请求,但拒绝执行该请求。',
'404': '服务器未找到请求的资源。',
'500': '服务器在处理请求时发生了未知的错误。',
};
function request<T>(url: string, config: RequestOptions): Promise<Response<T>> {
if (config === null || typeof config !== 'object') {
config = {};
}
if (config.headers && isPlainObject(config.headers)) {
config.headers = Object.assign({}, inital.headers, config.headers);
}
let { method, params, body, headers, credentials, responseType } = Object.assign({}, inital, config) as any;
if (typeof url !== 'string') throw new TypeError('url is not an string');
if (!/^http(s?):\/\//i.test(url)) url = baseURL + url;
if (params !== null) {
if (isPlainObject(params)) {
params = Qs.stringify(params);
}
url += `${url.includes('?') ? '&' : '?'}${params}`;
}
if (body !== null) {
if (isPlainObject(body)) {
let contentType = headers['Content-Type'] || 'application/json';
if (contentType.includes('urlencoded')) body = Qs.stringify(body);
if (contentType.includes('json')) body = JSON.stringify(body);
}
}
credentials = credentials ? 'include' : 'same-origin';
method = method.toUpperCase();
responseType = responseType.toUpperCase();
config = {
method,
credentials,
responseType,
};
if (/^(POST|PUT|PATCH)$/i.test(method)) {
config.body = body;
} else {
config.body = null;
}
return fetch(url, config as any).then(function onfulfilled(response) {
let { status, statusText } = response;
if (status >= 200 && status < 400) {
let result;
switch (responseType) {
case 'TEXT':
result = response.text();
break;
case 'JSON':
result = response.json();
break;
case 'BLOB':
result = response.blob();
break;
case 'ARRAYBUFFER':
result = response.arrayBuffer();
break;
}
// business code
result?.then(res => {
if (res?.code === 200) {
// console.log(':::');
}
});
return result;
}
let tip = codeMessage[String(status)];
notification.error({
message: tip,
});
return Promise.reject({
code: 'STATUS ERROR',
status,
statusText,
}).catch(function onrejected(reason) {
if (!navigator.onLine) {
message.error('好像断网了');
}
return Promise.reject(reason);
});
});
}
export default request;

@ -3176,15 +3176,6 @@ axe-core@^4.6.2:
resolved "https://registry.npmmirror.com/axe-core/-/axe-core-4.8.1.tgz#6948854183ee7e7eae336b9877c5bafa027998ea"
integrity sha512-9l850jDDPnKq48nbad8SiEelCv4OrUWrKab/cPj0GScVg6cb6NbCCt/Ulk26QEq5jP9NnGr04Bit1BHyV6r5CQ==
axios@^1.5.0:
version "1.5.0"
resolved "https://registry.npmmirror.com/axios/-/axios-1.5.0.tgz"
integrity sha512-D4DdjDo5CY50Qms0qGQTTw6Q44jl7zRwY7bthds06pUGfChBCTcQs+N743eFWGEd6pRTMd6A+I87aWyFV5wiZQ==
dependencies:
follow-redirects "^1.15.0"
form-data "^4.0.0"
proxy-from-env "^1.1.0"
axobject-query@^3.1.1:
version "3.2.1"
resolved "https://registry.npmmirror.com/axobject-query/-/axobject-query-3.2.1.tgz#39c378a6e3b06ca679f29138151e45b2b32da62a"
@ -5256,7 +5247,7 @@ flatted@^3.2.7:
resolved "https://registry.npmmirror.com/flatted/-/flatted-3.2.7.tgz#609f39207cb614b89d0765b477cb2d437fbf9787"
integrity sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ==
follow-redirects@^1.0.0, follow-redirects@^1.15.0:
follow-redirects@^1.0.0:
version "1.15.2"
resolved "https://registry.npmmirror.com/follow-redirects/-/follow-redirects-1.15.2.tgz#b460864144ba63f2681096f274c4e57026da2c13"
integrity sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==
@ -5296,15 +5287,6 @@ form-data@^3.0.0:
combined-stream "^1.0.8"
mime-types "^2.1.12"
form-data@^4.0.0:
version "4.0.0"
resolved "https://registry.npmmirror.com/form-data/-/form-data-4.0.0.tgz"
integrity sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==
dependencies:
asynckit "^0.4.0"
combined-stream "^1.0.8"
mime-types "^2.1.12"
forwarded@0.2.0:
version "0.2.0"
resolved "https://registry.npmmirror.com/forwarded/-/forwarded-0.2.0.tgz#2269936428aad4c15c7ebe9779a84bf0b2a81811"
@ -8477,11 +8459,6 @@ proxy-addr@~2.0.7:
forwarded "0.2.0"
ipaddr.js "1.9.1"
proxy-from-env@^1.1.0:
version "1.1.0"
resolved "https://registry.npmmirror.com/proxy-from-env/-/proxy-from-env-1.1.0.tgz"
integrity sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==
prr@~1.0.1:
version "1.0.1"
resolved "https://registry.npmmirror.com/prr/-/prr-1.0.1.tgz#d3fc114ba06995a45ec6893f484ceb1d78f5f476"
@ -8514,6 +8491,13 @@ qs@6.11.0:
dependencies:
side-channel "^1.0.4"
qs@^6.11.2:
version "6.11.2"
resolved "https://registry.npmmirror.com/qs/-/qs-6.11.2.tgz#64bea51f12c1f5da1bc01496f48ffcff7c69d7d9"
integrity sha512-tDNIz22aBzCDxLtVH++VnTfzxlfeK5CbqohpSqpJgj1Wg/cQbStNAz3NuqCs5vV+pjBsK4x4pN9HlVh7rcYRiA==
dependencies:
side-channel "^1.0.4"
querystringify@^2.1.1:
version "2.2.0"
resolved "https://registry.npmmirror.com/querystringify/-/querystringify-2.2.0.tgz#3345941b4153cb9d082d8eee4cda2016a9aef7f6"

Loading…
Cancel
Save