diff --git a/src/store/modules/auth/index.ts b/src/store/modules/auth/index.ts index 6b61c24..122ed7f 100644 --- a/src/store/modules/auth/index.ts +++ b/src/store/modules/auth/index.ts @@ -10,7 +10,7 @@ import { $t } from '@/locales'; import { useRouteStore } from '../route'; import { useTabStore } from '../tab'; import { clearAuthStorage, getToken } from './shared'; -import { apiRequestGet,apiRequestPost } from '@/utils/api'; +import { apiRequest } from '@/utils/api'; export const useAuthStore = defineStore(SetupStoreId.Auth, () => { const route = useRoute(); @@ -65,7 +65,7 @@ export const useAuthStore = defineStore(SetupStoreId.Auth, () => { startLoading(); let data = {username, password} - let response= await apiRequestPost('/auth/login',data); + let response= await apiRequest.post('/auth/login',data); let accessToken = response.data.token; let loginToken: Api.Auth.LoginToken = { token: accessToken, refreshToken: "" }; @@ -108,7 +108,7 @@ export const useAuthStore = defineStore(SetupStoreId.Auth, () => { } async function getUserInfo() { - let response = await apiRequestGet('/employees/getUserInfo'); + let response = await apiRequest.get('/employees/getUserInfo'); let data:any = response.data.data if (response.data.success) { diff --git a/src/utils/api.ts b/src/utils/api.ts index e173a98..f90e725 100644 --- a/src/utils/api.ts +++ b/src/utils/api.ts @@ -1,63 +1,80 @@ // api.ts -import axios from 'axios'; +import axios, { AxiosInstance, AxiosResponse, AxiosError } from 'axios'; import { localStg } from '@/utils/storage'; +import { useRouter } from 'vue-router'; -let baseUrl = import.meta.env.VITE_SERVICE_BASE_URL +// 环境变量获取 baseUrl +const baseUrl = import.meta.env.VITE_SERVICE_BASE_URL; -// 封装网络请求的接口 -export const apiRequest = async (method: 'GET' | 'POST' | 'PUT' | 'DELETE', path: string, data?: any) => { - let url = baseUrl + path; - const token = localStg.get('token'); // 获取 token - try { - const response = await axios({ - method, - url, - data, - headers: { - Authorization: `Bearer ${token}`, // 添加 Authorization 头 - }, - }); - return response.data; // 返回响应数据 - } catch (error) { - throw new Error('请求失败'); // 抛出错误 - } -}; +// 创建 axios 实例 +const apiClient: AxiosInstance = axios.create({ + baseURL: baseUrl, + timeout: 10000, // 设置请求超时时间 + headers: { + 'Content-Type': 'application/json', + }, +}); -export const apiRequestGet = async (path: string, params?:any) => { - let url = baseUrl + path; - const token = localStg.get('token'); // 获取 token - try { - return axios.get( - url, - { - headers: { - Authorization: `Bearer ${token}`, // 添加 Authorization 头 - }, - params: params, +// 请求拦截器 - 添加 token +apiClient.interceptors.request.use( + (config) => { + const token = localStg.get('token'); + if (token) { + config.headers.Authorization = `Bearer ${token}`; + } + return config; + }, + (error) => Promise.reject(error) +); + +// 响应拦截器 - 处理 401 等错误状态码 +apiClient.interceptors.response.use( + (response: AxiosResponse) => { + return response; // 直接返回响应数据 + }, + (error: AxiosError) => { + if (error.response) { + const status = error.response.status; + if (status === 401) { + // 清除本地储存的token + localStg.remove('token'); + // 获取路由实例并重定向到登录页面 + const router = useRouter(); + router.push('/login'); + return Promise.reject(new Error('未授权,请重新登录')); } - ); - } catch (error) { - throw new Error('请求失败'); // 抛出错误 + // 可以在这里处理其他状态码 + return Promise.reject(new Error(`请求失败:${status}`)); + } + return Promise.reject(error); } +); + +// 封装请求方法 +export const apiRequest = { + get: (url: string, params?: Record): Promise => { + return apiClient.get(url, { params }); + }, + + post: ( + url: string, + data?: Record, + params?: Record + ): Promise => { + return apiClient.post(url, data, { params }); + }, + + put: ( + url: string, + data?: Record, + params?: Record + ): Promise => { + return apiClient.put(url, data, { params }); + }, + + delete: (url: string, params?: Record): Promise => { + return apiClient.delete(url, { params }); + }, }; -export const apiRequestPost = async (path: string,data:any, params?:any) => { - let url = baseUrl + path; - const token = localStg.get('token'); // 获取 token - try { - return axios.post( - url, - data, - { - headers: { - Authorization: `Bearer ${token}`, // 添加 Authorization 头 - }, - params: params, - } - ); - } catch (error) { - throw new Error('请求失败'); // 抛出错误 - } -}; - -export default apiRequest; \ No newline at end of file +export default apiClient; \ No newline at end of file diff --git a/src/views/department/index.vue b/src/views/department/index.vue index 3a23025..c463636 100644 --- a/src/views/department/index.vue +++ b/src/views/department/index.vue @@ -76,7 +76,7 @@ import { ref, onMounted } from 'vue'; import { message, Modal } from 'ant-design-vue'; import axios from 'axios'; -import { apiRequestGet } from '@/utils/api'; +import { apiRequest } from '@/utils/api'; import { localStg } from '@/utils/storage'; // 部门树数据 @@ -103,7 +103,7 @@ const selectedKeys = ref([]); const fetchDepartments = async () => { try { loading.value = true; // 开始加载 - const response = await apiRequestGet('/department/allDepartment'); + const response = await apiRequest.get('/department/allDepartment'); if (response.data.success) { // 过滤重复数据并构建树结构 diff --git a/src/views/employee/list/index.vue b/src/views/employee/list/index.vue index 1f68041..d534e3f 100644 --- a/src/views/employee/list/index.vue +++ b/src/views/employee/list/index.vue @@ -31,7 +31,7 @@ import { message, Tag as ATag, Divider as ADivider } from 'ant-design-vue'; import axios from 'axios'; import { localStg } from '@/utils/storage'; - import { apiRequestGet } from '@/utils/api'; + import { apiRequest } from '@/utils/api'; // 表格列配置 const columns = [ { @@ -136,7 +136,7 @@ page: pagination.value.current, size: pagination.value.pageSize, } - const response = await apiRequestGet('/employees/allEmployees', params); + const response = await apiRequest.get('/employees/allEmployees', params); if (response.data.success) { dataSource.value = response.data.data; diff --git a/src/views/facility/index.vue b/src/views/facility/index.vue index ab53d3e..255c2ab 100644 --- a/src/views/facility/index.vue +++ b/src/views/facility/index.vue @@ -52,7 +52,7 @@ import { ref, reactive, onMounted } from 'vue'; import { message } from 'ant-design-vue'; import axios from 'axios'; -import {apiRequestGet} from '@/utils/api' +import { apiRequest } from '@/utils/api' // 表格列配置 const columns = [ @@ -100,7 +100,7 @@ const fetchData = async () => { code: searchForm.code || undefined, type: searchForm.type || undefined, }; - const response = await apiRequestGet('/facilities/list', params); + const response = await apiRequest.get('/facilities/list', params); if (response.data.success) { dataSource.value = response.data.data; pagination.total = response.data.total || response.data.data.length; diff --git a/src/views/orders/create/index.vue b/src/views/orders/create/index.vue index 6c110dd..c0c89be 100644 --- a/src/views/orders/create/index.vue +++ b/src/views/orders/create/index.vue @@ -39,7 +39,7 @@ import axios from 'axios'; // 用于 HTTP 请求 import { useRouter } from 'vue-router'; // 用于导航,假设您使用了 Vue Router import { localStg } from '@/utils/storage'; - import { apiRequestPost } from '@/utils/api'; // 假设您有一个 API 请求的工具函数 + import { apiRequest } from '@/utils/api'; // 假设您有一个 API 请求的工具函数 const formRef = ref(); // 表单引用 const router = useRouter(); // 获取路由实例 @@ -71,7 +71,7 @@ try { //await formRef.value.validate(); // 验证表单 - const response = await apiRequestPost('/work-orders', formState); // 发送 POST 请求 + const response = await apiRequest.post('/work-orders', formState); // 发送 POST 请求 if (response.data.success) { message.success('工单创建成功!'); diff --git a/src/views/orders/list/index.vue b/src/views/orders/list/index.vue index bd82c30..354206c 100644 --- a/src/views/orders/list/index.vue +++ b/src/views/orders/list/index.vue @@ -28,7 +28,7 @@ import { ref, onMounted } from 'vue'; import { Table as ATable, Tag as ATag } from 'ant-design-vue'; import axios from 'axios'; import { localStg } from '@/utils/storage'; -import { apiRequestGet } from '@/utils/api'; +import { apiRequest } from '@/utils/api'; // 表格列定义 const columns = [ { @@ -131,7 +131,7 @@ const fetchData = async (page = 1, pageSize = 10) => { const token = localStg.get('token'); // 替换为你的 token 键 try { - const response = await apiRequestGet('/work-orders/my-orders', + const response = await apiRequest.get('/work-orders/my-orders' // { // params: { // page: page - 1, // 后端通常从0开始计数 diff --git a/src/views/plan/index.vue b/src/views/plan/index.vue index 3086148..e317aba 100644 --- a/src/views/plan/index.vue +++ b/src/views/plan/index.vue @@ -37,7 +37,7 @@ import { ref, onMounted } from 'vue'; import axios from 'axios'; import dayjs from 'dayjs'; import { Tag } from 'ant-design-vue'; -import { apiRequestGet } from '@/utils/api'; +import { apiRequest } from '@/utils/api'; const columns = [ @@ -110,7 +110,7 @@ import { apiRequestGet } from '@/utils/api'; loading.value = true; try { // 模拟分页参数传递给后端 - const response = await apiRequestGet("/inspection-plans/employee/my-plan") + const response = await apiRequest.get("/inspection-plans/employee/my-plan") if (response.data.success) { planData.value = response.data.data;