mirror of https://github.com/longtai-cn/hippo4j
request by fetch utils done (#1461)
* fix: 合并代码 * feat: requst utils done --------- Co-authored-by: yikai <yikai@didiglobal.com>pull/1462/head
parent
a8cb04ed2d
commit
15dba8f456
File diff suppressed because it is too large
Load Diff
@ -1,128 +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,192 +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:
|
||||
}
|
||||
}
|
||||
}
|
@ -1,25 +0,0 @@
|
||||
"use strict";
|
||||
exports.__esModule = true;
|
||||
var react_1 = require("react");
|
||||
var styled_components_1 = require("styled-components");
|
||||
var antd_1 = require("antd");
|
||||
var useThemeMode_1 = require("@/hooks/useThemeMode");
|
||||
var index_module_less_1 = require("./index.module.less");
|
||||
var Header = antd_1.Layout.Header, Sider = antd_1.Layout.Sider, Content = antd_1.Layout.Content;
|
||||
var LayoutCom = function (props) {
|
||||
var sideMenuList = props.sideMenuList, children = props.children, _a = props.isSider, isSider = _a === void 0 ? true : _a;
|
||||
var myThemes = react_1.useContext(styled_components_1.ThemeContext);
|
||||
var _b = react_1.useState('mail'), current = _b[0], setCurrent = _b[1];
|
||||
var onClick = function (e) {
|
||||
setCurrent(e.key);
|
||||
};
|
||||
var setIsDark = useThemeMode_1["default"]()[0];
|
||||
return (React.createElement("main", { className: index_module_less_1["default"].container, style: { backgroundColor: myThemes.backgroundColor.bg1 } },
|
||||
React.createElement(Header, { className: index_module_less_1["default"].header, style: { backgroundColor: myThemes.backgroundColor.bg2 } },
|
||||
React.createElement(antd_1.Button, { onClick: function () { return setIsDark(function (pre) { return !pre; }); } }, "\u5207\u6362\u4E3B\u9898")),
|
||||
React.createElement(antd_1.Layout, { style: { backgroundColor: myThemes.backgroundColor.bg1, height: 'calc(100vh - 64px)' } },
|
||||
isSider && (React.createElement(Sider, { className: index_module_less_1["default"].sider, style: { backgroundColor: myThemes.backgroundColor.bg1 } },
|
||||
React.createElement(antd_1.Menu, { onClick: onClick, selectedKeys: [current], mode: "inline", items: sideMenuList }))),
|
||||
React.createElement(Content, { className: index_module_less_1["default"].content }, children))));
|
||||
};
|
||||
exports["default"] = LayoutCom;
|
@ -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>;
|
||||
};
|
@ -1,26 +0,0 @@
|
||||
"use strict";
|
||||
exports.__esModule = true;
|
||||
var layout_com_1 = require("./components/layout-com");
|
||||
var react_router_dom_1 = require("react-router-dom");
|
||||
var route_1 = require("./route");
|
||||
var login_1 = require("@/page/login");
|
||||
var icons_1 = require("@ant-design/icons");
|
||||
var sideMenuList = [
|
||||
{
|
||||
label: React.createElement("a", { href: "/about" }, "about"),
|
||||
key: 'mail',
|
||||
icon: React.createElement(icons_1.MailOutlined, null)
|
||||
},
|
||||
{
|
||||
label: React.createElement("a", { href: "/home" }, "\u4E3B\u9875"),
|
||||
key: 'app',
|
||||
icon: React.createElement(icons_1.AppstoreOutlined, null)
|
||||
},
|
||||
];
|
||||
var App = function () {
|
||||
return (React.createElement(layout_com_1["default"], { sideMenuList: sideMenuList, isSider: false },
|
||||
React.createElement(react_router_dom_1.Routes, null,
|
||||
React.createElement(react_router_dom_1.Route, { path: "/Login", Component: login_1["default"] }),
|
||||
route_1["default"].map(function (item) { return (React.createElement(react_router_dom_1.Route, { key: item.path, path: item.path, Component: item.component })); }))));
|
||||
};
|
||||
exports["default"] = App;
|
@ -0,0 +1,6 @@
|
||||
import React from 'react';
|
||||
|
||||
const HomeDetail = () => {
|
||||
return <></>;
|
||||
};
|
||||
export default HomeDetail;
|
@ -0,0 +1 @@
|
||||
export const Map = {};
|
@ -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,63 +0,0 @@
|
||||
"use strict";
|
||||
exports.__esModule = true;
|
||||
var antd_1 = require("antd");
|
||||
var user_1 = require("../../API/user");
|
||||
var Login = function (props) {
|
||||
var data = {
|
||||
passwordType: 'password',
|
||||
capsTooltip: false,
|
||||
loading: false,
|
||||
showDialog: false,
|
||||
redirect: undefined,
|
||||
otherQuery: {},
|
||||
loginForm: {
|
||||
username: '',
|
||||
password: ''
|
||||
}
|
||||
};
|
||||
var validatePassword = function (_, value) {
|
||||
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();
|
||||
};
|
||||
var form = antd_1.Form.useForm()[0];
|
||||
var onFinish = function () {
|
||||
var 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;
|
||||
user_1["default"](loginParams)
|
||||
.then(function (resolve) {
|
||||
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"](function (e) {
|
||||
console.log('login error.', e);
|
||||
data.loading = false;
|
||||
});
|
||||
};
|
||||
return (React.createElement("div", { className: "login-container" },
|
||||
React.createElement(antd_1.Form, { name: "loginForm", form: form, onFinish: onFinish, style: { maxWidth: 600 } },
|
||||
React.createElement("div", { className: "title-container" },
|
||||
React.createElement("h3", { className: "title" }, "\u4F60\u597D\u5440")),
|
||||
React.createElement(antd_1.Form.Item, { name: "username", label: "\u7528\u6237\u540D", rules: [{ required: true, message: 'Username is required' }] },
|
||||
React.createElement(antd_1.Input, { placeholder: "\u7528\u6237\u540D" })),
|
||||
React.createElement(antd_1.Form.Item, { name: "password", label: "\u5BC6\u7801", rules: [{ validator: validatePassword }, { required: true, message: 'Street is required' }] },
|
||||
React.createElement(antd_1.Input, { placeholder: "\u5BC6\u7801" })),
|
||||
React.createElement(antd_1.Form.Item, { name: "submit" },
|
||||
React.createElement(antd_1.Button, { type: "primary", htmlType: "submit", className: "login-button" }, "\u767B\u5F55")))));
|
||||
};
|
||||
exports["default"] = Login;
|
@ -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;
|
File diff suppressed because it is too large
Load Diff
Loading…
Reference in new issue