[style] 封装了新的api接口

This commit is contained in:
LiuYuanchi 2025-04-28 17:18:49 +08:00
parent c6d0c38232
commit 903cf139dc
8 changed files with 86 additions and 69 deletions

View File

@ -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) {

View File

@ -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: <T>(url: string, params?: Record<string, any>): Promise<T> => {
return apiClient.get(url, { params });
},
post: <T>(
url: string,
data?: Record<string, any>,
params?: Record<string, any>
): Promise<T> => {
return apiClient.post(url, data, { params });
},
put: <T>(
url: string,
data?: Record<string, any>,
params?: Record<string, any>
): Promise<T> => {
return apiClient.put(url, data, { params });
},
delete: <T>(url: string, params?: Record<string, any>): Promise<T> => {
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;
export default apiClient;

View File

@ -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) {
//

View File

@ -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;

View File

@ -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;

View File

@ -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('工单创建成功!');

View File

@ -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

View File

@ -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;