From 40b3be8a8d7568a980a674e98a80bcb903ef19db Mon Sep 17 00:00:00 2001 From: luchang <835498386@qq.com> Date: Fri, 31 May 2024 13:37:52 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/config.dev.ts | 2 +- config/config.prod.ts | 2 +- config/defaultSettings.ts | 2 +- config/proxy.ts | 3 +- src/app.tsx | 37 +++-- src/components/Banner/Upload.tsx | 23 ++-- .../RightContent/AvatarDropdown.tsx | 5 +- src/locales/en-US/pages.ts | 4 +- src/locales/zh-CN/pages.ts | 4 +- src/pages/User/Login/index.tsx | 126 ++---------------- src/pages/UserList.tsx | 1 + src/requestErrorConfig.ts | 10 +- src/services/ant-design-pro/api.ts | 20 +-- 13 files changed, 70 insertions(+), 169 deletions(-) diff --git a/config/config.dev.ts b/config/config.dev.ts index 2db770e..915b1c0 100644 --- a/config/config.dev.ts +++ b/config/config.dev.ts @@ -3,7 +3,7 @@ import { defineConfig } from '@umijs/max'; export default defineConfig({ define: { 'process.env': { - API_HOST_URL: 'http://localhost:4399', + API_HOST_URL: 'http://127.0.0.1:4399', }, }, }); diff --git a/config/config.prod.ts b/config/config.prod.ts index 2db770e..4f528c1 100644 --- a/config/config.prod.ts +++ b/config/config.prod.ts @@ -3,7 +3,7 @@ import { defineConfig } from '@umijs/max'; export default defineConfig({ define: { 'process.env': { - API_HOST_URL: 'http://localhost:4399', + API_HOST_URL: 'https://api.easy-trip.world/api', }, }, }); diff --git a/config/defaultSettings.ts b/config/defaultSettings.ts index 0640bde..bdf693b 100644 --- a/config/defaultSettings.ts +++ b/config/defaultSettings.ts @@ -15,7 +15,7 @@ const Settings: ProLayoutProps & { fixedHeader: false, fixSiderbar: true, colorWeak: false, - title: '依图', + title: '依途', pwa: true, logo: 'https://polaris-frontend.oss-cn-shanghai.aliyuncs.com/yitu_image/logo.png', iconfontUrl: '', diff --git a/config/proxy.ts b/config/proxy.ts index 7f1653a..afeb59f 100644 --- a/config/proxy.ts +++ b/config/proxy.ts @@ -9,7 +9,7 @@ * * @doc https://umijs.org/docs/guides/proxy */ -const { API_HOST_URL = 'localhost:3000' } = process.env; +const { API_HOST_URL = 'localhost:4399' } = process.env; export default { // 如果需要自定义本地开发服务器 请取消注释按需调整 dev: { @@ -23,5 +23,4 @@ export default { pathRewrite: { '^': '' }, }, }, - }; diff --git a/src/app.tsx b/src/app.tsx index 88e5679..3f721c7 100644 --- a/src/app.tsx +++ b/src/app.tsx @@ -22,9 +22,7 @@ export async function getInitialState(): Promise<{ }> { const fetchUserInfo = async () => { try { - const msg = await queryCurrentUser({ - skipErrorHandler: true, - }); + const msg = await queryCurrentUser(); return msg.data; } catch (error) { // history.push(loginPath); @@ -33,14 +31,14 @@ export async function getInitialState(): Promise<{ }; // 如果不是登录页面,执行 const { location } = history; - // if (location.pathname !== loginPath) { - // const currentUser = await fetchUserInfo(); - // return { - // fetchUserInfo, - // currentUser, - // settings: defaultSettings as Partial, - // }; - // } + if (location.pathname !== loginPath) { + const currentUser = await fetchUserInfo(); + return { + fetchUserInfo, + currentUser, + settings: defaultSettings as Partial, + }; + } return { fetchUserInfo, settings: defaultSettings as Partial, @@ -55,8 +53,7 @@ export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) = src: initialState?.currentUser?.avatar, title: , render: (_, avatarChildren) => { - return <>admin - // return {avatarChildren}; + return {avatarChildren}; }, }, waterMarkProps: { @@ -66,9 +63,9 @@ export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) = onPageChange: () => { const { location } = history; // 如果没有登录,重定向到 login - // if (!initialState?.currentUser && location.pathname !== loginPath) { - // history.push(loginPath); - // } + if (!initialState?.currentUser && location.pathname !== loginPath) { + history.push(loginPath); + } }, bgLayoutImgList: [ { @@ -92,10 +89,10 @@ export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) = ], links: isDev ? [ - - - OpenAPI 文档 - , + // + // + // OpenAPI 文档 + // , ] : [], menuHeaderRender: undefined, diff --git a/src/components/Banner/Upload.tsx b/src/components/Banner/Upload.tsx index 8f50444..46b3ca4 100644 --- a/src/components/Banner/Upload.tsx +++ b/src/components/Banner/Upload.tsx @@ -21,16 +21,16 @@ const FormUpload: React.FC = ({ onChange }) => { const [imageUrl, setImageUrl] = useState(''); const handleUpload = async (info: any) => { - if (info.file.status === 'uploading') { - setLoading(true); - return; - } - if (info.file.status === 'done') { - getBase64(info.file.originFileObj as FileType, (url) => { - setLoading(false); - setImageUrl(url); - }); - } + // if (info.file.status === 'uploading') { + // setLoading(true); + // return; + // } + // if (info.file.status === 'done') { + getBase64(info.file.originFileObj as FileType, (url) => { + setLoading(false); + setImageUrl(url); + }); + // } onChange?.(info); }; @@ -58,6 +58,9 @@ const FormUpload: React.FC = ({ onChange }) => { className={`avatar-uploader uploadBtn`} showUploadList={false} onChange={handleUpload} + customRequest={(file: any) => { + console.log('>>>>>测试', file); + }} > {uploadButton} diff --git a/src/components/RightContent/AvatarDropdown.tsx b/src/components/RightContent/AvatarDropdown.tsx index 766a5d3..f511c76 100644 --- a/src/components/RightContent/AvatarDropdown.tsx +++ b/src/components/RightContent/AvatarDropdown.tsx @@ -17,7 +17,7 @@ export type GlobalHeaderRightProps = { export const AvatarName = () => { const { initialState } = useModel('@@initialState'); const { currentUser } = initialState || {}; - return {currentUser?.name}; + return {currentUser?.username}; }; const useStyles = createStyles(({ token }) => { @@ -43,7 +43,6 @@ export const AvatarDropdown: React.FC = ({ menu, childre * 退出登录,并且将当前的 url 保存 */ const loginOut = async () => { - await outLogin(); const { search, pathname } = window.location; const urlParams = new URL(window.location.href).searchParams; /** 此方法会跳转到 redirect 参数所在的位置 */ @@ -95,7 +94,7 @@ export const AvatarDropdown: React.FC = ({ menu, childre const { currentUser } = initialState; - if (!currentUser || !currentUser.name) { + if (!currentUser || !currentUser.username) { return loading; } diff --git a/src/locales/en-US/pages.ts b/src/locales/en-US/pages.ts index 3334c03..09349ff 100644 --- a/src/locales/en-US/pages.ts +++ b/src/locales/en-US/pages.ts @@ -5,9 +5,9 @@ export default { 'pages.login.accountLogin.errorMessage': 'Incorrect username/password(admin/ant.design)', 'pages.login.failure': 'Login failed, please try again!', 'pages.login.success': 'Login successful!', - 'pages.login.username.placeholder': 'Username: admin or user', + 'pages.login.username.placeholder': 'Username: admin', 'pages.login.username.required': 'Please input your username!', - 'pages.login.password.placeholder': 'Password: ant.design', + 'pages.login.password.placeholder': 'Password', 'pages.login.password.required': 'Please input your password!', 'pages.login.phoneLogin.tab': 'Phone Login', 'pages.login.phoneLogin.errorMessage': 'Verification Code Error', diff --git a/src/locales/zh-CN/pages.ts b/src/locales/zh-CN/pages.ts index a266bc6..9895568 100644 --- a/src/locales/zh-CN/pages.ts +++ b/src/locales/zh-CN/pages.ts @@ -4,9 +4,9 @@ export default { 'pages.login.accountLogin.errorMessage': '错误的用户名和密码(admin/ant.design)', 'pages.login.failure': '登录失败,请重试!', 'pages.login.success': '登录成功!', - 'pages.login.username.placeholder': '用户名: admin or user', + 'pages.login.username.placeholder': '用户名: admin', 'pages.login.username.required': '用户名是必填项!', - 'pages.login.password.placeholder': '密码: ant.design', + 'pages.login.password.placeholder': '密码', 'pages.login.password.required': '密码是必填项!', 'pages.login.phoneLogin.tab': '手机号登录', 'pages.login.phoneLogin.errorMessage': '验证码错误', diff --git a/src/pages/User/Login/index.tsx b/src/pages/User/Login/index.tsx index f2caf13..1165f44 100644 --- a/src/pages/User/Login/index.tsx +++ b/src/pages/User/Login/index.tsx @@ -91,18 +91,19 @@ const Login: React.FC = () => { const handleSubmit = async (values: API.LoginParams) => { try { // 登录 - const msg = await login({ ...values, type }); - if (msg.status === 'ok') { + const result = await login({ ...values, type }); + if (result.code === 0) { const defaultLoginSuccessMessage = intl.formatMessage({ id: 'pages.login.success', defaultMessage: '登录成功!', }); message.success(defaultLoginSuccessMessage); - // await fetchUserInfo(); + localStorage.setItem('token', result.data.token); + await fetchUserInfo(); history.push('/userList'); return; } - console.log(msg); + console.log(result); // 如果失败去设置用户错误信息 setUserLoginState(msg); } catch (error) { @@ -151,28 +152,6 @@ const Login: React.FC = () => { await handleSubmit(values as API.LoginParams); }} > - {/* */} - {status === 'error' && loginType === 'account' && ( { }} placeholder={intl.formatMessage({ id: 'pages.login.username.placeholder', - defaultMessage: '用户名: admin or user', + defaultMessage: '请输入用户名!', })} rules={[ { @@ -213,7 +192,7 @@ const Login: React.FC = () => { }} placeholder={intl.formatMessage({ id: 'pages.login.password.placeholder', - defaultMessage: '密码: ant.design', + defaultMessage: '请输入密码', })} rules={[ { @@ -229,103 +208,18 @@ const Login: React.FC = () => { /> )} - - {/* {status === 'error' && loginType === 'mobile' && } - {type === 'mobile' && ( - <> - , - }} - name="mobile" - placeholder={intl.formatMessage({ - id: 'pages.login.phoneNumber.placeholder', - defaultMessage: '手机号', - })} - rules={[ - { - required: true, - message: ( - - ), - }, - { - pattern: /^1\d{10}$/, - message: ( - - ), - }, - ]} - /> - , - }} - captchaProps={{ - size: 'large', - }} - placeholder={intl.formatMessage({ - id: 'pages.login.captcha.placeholder', - defaultMessage: '请输入验证码', - })} - captchaTextRender={(timing, count) => { - if (timing) { - return `${count} ${intl.formatMessage({ - id: 'pages.getCaptchaSecondText', - defaultMessage: '获取验证码', - })}`; - } - return intl.formatMessage({ - id: 'pages.login.phoneLogin.getVerificationCode', - defaultMessage: '获取验证码', - }); - }} - name="captcha" - rules={[ - { - required: true, - message: ( - - ), - }, - ]} - onGetCaptcha={async (phone) => { - const result = await getFakeCaptcha({ - phone, - }); - if (!result) { - return; - } - message.success('获取验证码成功!验证码为:1234'); - }} - /> - - )} */} - {/*
- - - - +
*/} diff --git a/src/pages/UserList.tsx b/src/pages/UserList.tsx index 3078178..4566246 100644 --- a/src/pages/UserList.tsx +++ b/src/pages/UserList.tsx @@ -110,6 +110,7 @@ const Welcome: React.FC = () => { scroll={{ x: 960, }} + recordCreatorProps={false} loading={false} columns={columns} request={request} diff --git a/src/requestErrorConfig.ts b/src/requestErrorConfig.ts index 4f88845..30a4e8c 100644 --- a/src/requestErrorConfig.ts +++ b/src/requestErrorConfig.ts @@ -1,5 +1,5 @@ import type { RequestOptions } from '@@/plugin-request/request'; -import type { RequestConfig } from '@umijs/max'; +import type { RequestConfig, history } from '@umijs/max'; import { message, notification } from 'antd'; // 错误处理方案: 错误类型 @@ -32,6 +32,7 @@ export const errorConfig: RequestConfig = { errorThrower: (res) => { const { success, data, errorCode, errorMessage, showType } = res as unknown as ResponseStructure; + if (!success) { const error: any = new Error(errorMessage); error.name = 'BizError'; @@ -75,6 +76,9 @@ export const errorConfig: RequestConfig = { // Axios 的错误 // 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围 message.error(`Response status:${error.response.status}`); + if (error.response.status === 401) { + window.location.href = '/user/login'; + } } else if (error.request) { // 请求已经成功发起,但没有收到响应 // \`error.request\` 在浏览器中是 XMLHttpRequest 的实例, @@ -92,6 +96,10 @@ export const errorConfig: RequestConfig = { (config: RequestOptions) => { // 拦截请求配置,进行个性化处理。 const url = config?.url?.concat(); + const token = localStorage.getItem('token'); + if (token && config.headers) { + config.headers.Authorization = `Bearer ${token}`; + } return { ...config, url }; }, ], diff --git a/src/services/ant-design-pro/api.ts b/src/services/ant-design-pro/api.ts index b0957e1..80231c5 100644 --- a/src/services/ant-design-pro/api.ts +++ b/src/services/ant-design-pro/api.ts @@ -6,7 +6,7 @@ import { request } from '@umijs/max'; export async function currentUser(options?: { [key: string]: any }) { return request<{ data: API.CurrentUser; - }>('/api/currentUser', { + }>('/auth/user', { method: 'GET', ...(options || {}), }); @@ -22,7 +22,7 @@ export async function outLogin(options?: { [key: string]: any }) { /** 登录接口 POST /api/login/account */ export async function login(body: API.LoginParams, options?: { [key: string]: any }) { - return request('/api/user/login', { + return request('/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json', @@ -34,7 +34,7 @@ export async function login(body: API.LoginParams, options?: { [key: string]: an /** 获取用户列表 */ export async function getUserList(options?: { [key: string]: any }) { - return request('/api/user', { + return request('/user', { method: 'GET', ...(options || {}), }); @@ -42,7 +42,7 @@ export async function getUserList(options?: { [key: string]: any }) { /** 编辑用户 */ export async function updateUser(body: any, options?: { [key: string]: any }) { - return request('/api/user/' + body?.id, { + return request('/user/' + body?.id, { method: 'PATCH', data: body, ...(options || {}), @@ -51,7 +51,7 @@ export async function updateUser(body: any, options?: { [key: string]: any }) { /** 删除用户 */ export async function deleteUser(options?: { [key: string]: any }) { - return request('/api/user/' + options?.id, { + return request('/user/' + options?.id, { method: 'DELETE', ...(options || {}), }); @@ -59,7 +59,7 @@ export async function deleteUser(options?: { [key: string]: any }) { /** 获取oss签名 */ export async function getSignature(options?: { [key: string]: any }) { - return request('/api/signature', { + return request('/signature', { method: 'GET', ...(options || {}), }); @@ -75,7 +75,7 @@ export async function upload(url: string, formData: any) { /** 上传banner图 */ export async function uploadBanner(body: any, options?: { [key: string]: any }) { - return request('/api/banner', { + return request('/banner', { method: 'POST', headers: { 'Content-Type': 'application/json', @@ -87,7 +87,7 @@ export async function uploadBanner(body: any, options?: { [key: string]: any }) /** 删除 */ export async function getBanners(options?: { [key: string]: any }) { - return request('/api/banner', { + return request('/banner', { method: 'GET', ...(options || {}), }); @@ -95,7 +95,7 @@ export async function getBanners(options?: { [key: string]: any }) { /** 删除 */ export async function deleteBanner(id: number) { - return request('/api/banner/' + id, { + return request('/banner/' + id, { method: 'DELETE', headers: { 'Content-Type': 'application/json', @@ -105,7 +105,7 @@ export async function deleteBanner(id: number) { /** 此处后端没有提供注释 GET /api/notices */ export async function getNotices(options?: { [key: string]: any }) { - return request('/api/notices', { + return request('/notices', { method: 'GET', ...(options || {}), });