diff --git a/src/api/index.js b/src/api/index.js index 2e3ac83..bbb9df8 100644 --- a/src/api/index.js +++ b/src/api/index.js @@ -2,5 +2,5 @@ import request from '@/utils/http' export default { getUser: () => request.get('/user'), - refreshToken: () => request.post('/auth/refreshToken'), + refreshToken: () => request.post('/auth/refreshToken', null, { noNeedTip: true }), } diff --git a/src/components/table/CrudTable.vue b/src/components/table/CrudTable.vue index 3d88e70..acd0900 100644 --- a/src/components/table/CrudTable.vue +++ b/src/components/table/CrudTable.vue @@ -93,7 +93,6 @@ async function handleQuery() { } catch (error) { tableData.value = [] pagination.itemCount = 0 - $message.error(error.message) } finally { loading.value = false } @@ -103,7 +102,11 @@ function handleSearch() { handleQuery() } async function handleReset() { - emit('update:queryItems', { ...initQuery }) + const queryItems = { ...props.queryItems } + for (const key in queryItems) { + queryItems[key] = '' + } + emit('update:queryItems', { ...queryItems, ...initQuery }) await nextTick() pagination.page = 1 handleQuery() diff --git a/src/composables/useCRUD.js b/src/composables/useCRUD.js index e2ea6f7..44cb782 100644 --- a/src/composables/useCRUD.js +++ b/src/composables/useCRUD.js @@ -1,4 +1,4 @@ -import { isNullOrWhitespace } from '../utils/is' +import { isNullOrWhitespace } from '@/utils/is' const ACTIONS = { view: '查看', @@ -62,7 +62,6 @@ export default function ({ name, initForm = {}, doCreate, doDelete, doUpdate, re modalLoading.value = modalVisible.value = false data && refresh(data) } catch (error) { - $message.error('操作失败') modalLoading.value = false } }) diff --git a/src/router/guard/permission-guard.js b/src/router/guard/permission-guard.js index 64b42c8..2c80b7d 100644 --- a/src/router/guard/permission-guard.js +++ b/src/router/guard/permission-guard.js @@ -1,11 +1,10 @@ import { useUserStore } from '@/store/modules/user' import { usePermissionStore } from '@/store/modules/permission' import { NOT_FOUND_ROUTE } from '@/router/routes' -import { getToken, refreshAccessToken, removeToken } from '@/utils/token' -import { toLogin } from '@/utils/auth' +import { getToken, refreshAccessToken } from '@/utils/token' import { isNullOrWhitespace } from '@/utils/is' -const WHITE_LIST = ['/login'] +const WHITE_LIST = ['/login', '/404'] export function createPermissionGuard(router) { const userStore = useUserStore() const permissionStore = usePermissionStore() @@ -19,24 +18,25 @@ export function createPermissionGuard(router) { } /** 有token的情况 */ - if (to.path === '/login') return { path: '/', replace: true } + if (to.path === '/404') return true // 已经拿到用户信息 if (userStore.userId) { refreshAccessToken() return true } - await userStore.getUserInfo().catch((error) => { - removeToken() - toLogin() - $message.error(error.message || '获取用户信息失败!') - }) - const accessRoutes = permissionStore.generateRoutes(userStore.role) - accessRoutes.forEach((route) => { - !router.hasRoute(route.name) && router.addRoute(route) - }) - router.addRoute(NOT_FOUND_ROUTE) - return { ...to, replace: true } + try { + await userStore.getUserInfo() + const accessRoutes = permissionStore.generateRoutes(userStore.role) + accessRoutes.forEach((route) => { + !router.hasRoute(route.name) && router.addRoute(route) + }) + router.addRoute(NOT_FOUND_ROUTE) + return { ...to, replace: true } + } catch (error) { + console.error(error) + return + } }) } diff --git a/src/store/modules/user.js b/src/store/modules/user.js index 2d15164..1807fad 100644 --- a/src/store/modules/user.js +++ b/src/store/modules/user.js @@ -27,13 +27,9 @@ export const useUserStore = defineStore('user', { async getUserInfo() { try { const res = await api.getUser() - if (res.code === 0) { - const { id, name, avatar, role } = res.data - this.userInfo = { id, name, avatar, role } - return Promise.resolve(res.data) - } else { - return Promise.reject(res) - } + const { id, name, avatar, role } = res.data + this.userInfo = { id, name, avatar, role } + return Promise.resolve(res.data) } catch (error) { return Promise.reject(error) } diff --git a/src/utils/auth.js b/src/utils/auth.js index 9edfad4..17a0926 100644 --- a/src/utils/auth.js +++ b/src/utils/auth.js @@ -6,3 +6,9 @@ export function toLogin() { query: { ...router.currentRoute.value.query, redirect: router.currentRoute.value.path }, }) } + +export function toFourZeroFour() { + router.replace({ + path: '/404', + }) +} diff --git a/src/utils/common/naiveTools.js b/src/utils/common/naiveTools.js index cf17088..c741d65 100644 --- a/src/utils/common/naiveTools.js +++ b/src/utils/common/naiveTools.js @@ -9,7 +9,7 @@ export function setupMessage(NMessage) { * * loading message不会自动清除,除非被替换成非loading message,非loading message默认2秒后自动清除 */ - removeMessage(message, duration = 2000) { + removeMessage(message = loadingMessage, duration = 2000) { setTimeout(() => { if (message) { message.destroy() diff --git a/src/utils/http/helpers.js b/src/utils/http/helpers.js index b778b6f..617779f 100644 --- a/src/utils/http/helpers.js +++ b/src/utils/http/helpers.js @@ -1,4 +1,7 @@ import { useUserStore } from '@/store/modules/user' +import { isNullOrUndef } from '@/utils/is' +import { removeToken } from '@/utils/token' +import { toLogin } from '@/utils/auth' const WITHOUT_TOKEN_API = [{ url: '/auth/login', method: 'POST' }] @@ -11,3 +14,36 @@ export function addBaseParams(params) { params.userId = useUserStore().userId } } + +export function resolveResError(error = {}) { + let { code, message } = error + if (isNullOrUndef(code)) { + // 未知错误 + code = -1 + message = message ?? '接口未知异常!' + } else { + switch (code) { + case 400: + message = message ?? '请求参数错误' + break + case 401: + message = message ?? '登录已过期' + removeToken() + toLogin() + break + case 403: + message = message ?? '没有权限' + break + case 404: + message = message ?? '资源或接口不存在' + break + case 500: + message = message ?? '服务器异常' + break + default: + message = message ?? '操作异常!' + break + } + } + return { code, message } +} diff --git a/src/utils/http/interceptors.js b/src/utils/http/interceptors.js index 51ce7d8..9ed9570 100644 --- a/src/utils/http/interceptors.js +++ b/src/utils/http/interceptors.js @@ -1,14 +1,8 @@ import { getToken } from '@/utils/token' import { toLogin } from '@/utils/auth' -import { isNullOrUndef } from '@/utils/is' -import { isWithoutToken } from './helpers' +import { isWithoutToken, resolveResError } from './helpers' export function reqResolve(config) { - // 防止缓存,给get请求加上时间戳 - if (config.method === 'get') { - config.params = { ...config.params, t: new Date().getTime() } - } - // 处理不需要token的请求 if (isWithoutToken(config)) { return config @@ -35,42 +29,18 @@ export function reqReject(error) { } export function repResolve(response) { - if (response?.data?.code !== 0) { - $message.error(response?.data?.message || '操作异常') - return Promise.reject(response?.data) + const { noNeedTip } = response.config + if (response.data?.code !== 0) { + const { code, message } = resolveResError(response?.data) + !noNeedTip && $message.error(message) + return Promise.reject({ code, message, error: response?.data }) } return Promise.resolve(response?.data) } export function repReject(error) { - let { code, message } = error.response?.data || {} - if (isNullOrUndef(code)) { - // 未知错误 - code = -1 - message = '接口异常!' - } else { - /** - * TODO 此处可以根据后端返回的错误码自定义框架层面的错误处理 - */ - switch (code) { - case 400: - message = message || '请求参数错误' - break - case 401: - message = message || '登录已过期' - break - case 403: - message = message || '没有权限' - break - case 404: - message = message || '资源或接口不存在' - break - default: - message = message || '未知异常' - break - } - } - console.error(`【${code}】 ${error}`) - $message.error(message || '操作异常') + const { noNeedTip } = error.response?.config || error.config + const { code, message } = resolveResError(error.response?.data) + !noNeedTip && $message.error(message) return Promise.reject({ code, message, error }) } diff --git a/src/utils/token.js b/src/utils/token.js index 45bf364..343137c 100644 --- a/src/utils/token.js +++ b/src/utils/token.js @@ -26,8 +26,6 @@ export async function refreshAccessToken() { if (new Date().getTime() - time <= 1000 * 60 * 30) return try { const res = await api.refreshToken() - if (res.code === 0) { - setToken(res.data.token) - } + setToken(res.data.token) } catch (error) {} } diff --git a/src/views/examples/table/post/api.js b/src/views/examples/table/post/api.js index d17fbdf..79669b7 100644 --- a/src/views/examples/table/post/api.js +++ b/src/views/examples/table/post/api.js @@ -5,5 +5,5 @@ export default { getPostById: (id) => request.get(`/post/${id}`), addPost: (data) => request.post('/post', data), updatePost: (data) => request.put(`/post/${data.id}`, data), - deletePost: (id) => request.delete(`/post/${id}`), + deletePost: (id) => request.delete(`/post/${id}`, null), } diff --git a/src/views/examples/table/post/index.vue b/src/views/examples/table/post/index.vue index 7af4293..c771ebc 100644 --- a/src/views/examples/table/post/index.vue +++ b/src/views/examples/table/post/index.vue @@ -90,9 +90,7 @@ import { isNullOrUndef } from '@/utils/is' const $table = ref(null) /** QueryBar筛选参数(可选) */ -const queryItems = ref({ - title: '', -}) +const queryItems = ref({}) /** 补充参数(可选) */ const extraParams = ref({}) diff --git a/src/views/examples/table/post/usePostTable.js b/src/views/examples/table/post/usePostTable.js index d1548b9..9da9632 100644 --- a/src/views/examples/table/post/usePostTable.js +++ b/src/views/examples/table/post/usePostTable.js @@ -163,12 +163,8 @@ export const usePostTable = () => { async function getTableData() { try { - const res = await api.getPosts() - if (res.code === 0) { - return res.data - } - console.warn(res.message) - return [] + const { data } = await api.getPosts() + return data } catch (error) { console.error(error) return [] diff --git a/src/views/login/index.vue b/src/views/login/index.vue index 9eb665f..aecd734 100644 --- a/src/views/login/index.vue +++ b/src/views/login/index.vue @@ -81,29 +81,26 @@ async function handleLogin() { return } try { - $message.loading('正在验证...') loging.value = true + $message.loading('正在验证...') const res = await api.login({ name, password: password.toString() }) - if (res.code === 0) { - $message.success('登录成功') - setToken(res.data.token) - if (isRemember.value) { - lStorage.set('loginInfo', { name, password }) - } else { - lStorage.remove('loginInfo') - } - if (query.redirect) { - const path = query.redirect - Reflect.deleteProperty(query, 'redirect') - router.push({ path, query }) - } else { - router.push('/') - } + $message.success('登录成功') + setToken(res.data.token) + if (isRemember.value) { + lStorage.set('loginInfo', { name, password }) } else { - $message.warning(res.message) + lStorage.remove('loginInfo') + } + if (query.redirect) { + const path = query.redirect + Reflect.deleteProperty(query, 'redirect') + router.push({ path, query }) + } else { + router.push('/') } } catch (error) { - $message.error(error.message) + console.error(error) + $message.removeMessage() } loging.value = false }