[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 { useRouteStore } from '../route';
import { useTabStore } from '../tab'; import { useTabStore } from '../tab';
import { clearAuthStorage, getToken } from './shared'; import { clearAuthStorage, getToken } from './shared';
import { apiRequestGet,apiRequestPost } from '@/utils/api'; import { apiRequest } from '@/utils/api';
export const useAuthStore = defineStore(SetupStoreId.Auth, () => { export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
const route = useRoute(); const route = useRoute();
@ -65,7 +65,7 @@ export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
startLoading(); startLoading();
let data = {username, password} 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 accessToken = response.data.token;
let loginToken: Api.Auth.LoginToken = { token: accessToken, refreshToken: "" }; let loginToken: Api.Auth.LoginToken = { token: accessToken, refreshToken: "" };
@ -108,7 +108,7 @@ export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
} }
async function getUserInfo() { async function getUserInfo() {
let response = await apiRequestGet('/employees/getUserInfo'); let response = await apiRequest.get('/employees/getUserInfo');
let data:any = response.data.data let data:any = response.data.data
if (response.data.success) { if (response.data.success) {

View File

@ -1,63 +1,80 @@
// api.ts // api.ts
import axios from 'axios'; import axios, { AxiosInstance, AxiosResponse, AxiosError } from 'axios';
import { localStg } from '@/utils/storage'; 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;
// 封装网络请求的接口 // 创建 axios 实例
export const apiRequest = async (method: 'GET' | 'POST' | 'PUT' | 'DELETE', path: string, data?: any) => { const apiClient: AxiosInstance = axios.create({
let url = baseUrl + path; baseURL: baseUrl,
const token = localStg.get('token'); // 获取 token timeout: 10000, // 设置请求超时时间
try { headers: {
const response = await axios({ 'Content-Type': 'application/json',
method, },
url, });
data,
headers: {
Authorization: `Bearer ${token}`, // 添加 Authorization 头
},
});
return response.data; // 返回响应数据
} catch (error) {
throw new Error('请求失败'); // 抛出错误
}
};
export const apiRequestGet = async (path: string, params?:any) => { // 请求拦截器 - 添加 token
let url = baseUrl + path; apiClient.interceptors.request.use(
const token = localStg.get('token'); // 获取 token (config) => {
try { const token = localStg.get('token');
return axios.get( if (token) {
url, config.headers.Authorization = `Bearer ${token}`;
{ }
headers: { return config;
Authorization: `Bearer ${token}`, // 添加 Authorization 头 },
}, (error) => Promise.reject(error)
params: params, );
// 响应拦截器 - 处理 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) { return Promise.reject(new Error(`请求失败:${status}`));
throw new Error('请求失败'); // 抛出错误 }
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) => { export default apiClient;
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;

View File

@ -76,7 +76,7 @@
import { ref, onMounted } from 'vue'; import { ref, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue'; import { message, Modal } from 'ant-design-vue';
import axios from 'axios'; import axios from 'axios';
import { apiRequestGet } from '@/utils/api'; import { apiRequest } from '@/utils/api';
import { localStg } from '@/utils/storage'; import { localStg } from '@/utils/storage';
// //
@ -103,7 +103,7 @@ const selectedKeys = ref([]);
const fetchDepartments = async () => { const fetchDepartments = async () => {
try { try {
loading.value = true; // loading.value = true; //
const response = await apiRequestGet('/department/allDepartment'); const response = await apiRequest.get('/department/allDepartment');
if (response.data.success) { if (response.data.success) {
// //

View File

@ -31,7 +31,7 @@
import { message, Tag as ATag, Divider as ADivider } from 'ant-design-vue'; import { message, Tag as ATag, Divider as ADivider } from 'ant-design-vue';
import axios from 'axios'; import axios from 'axios';
import { localStg } from '@/utils/storage'; import { localStg } from '@/utils/storage';
import { apiRequestGet } from '@/utils/api'; import { apiRequest } from '@/utils/api';
// //
const columns = [ const columns = [
{ {
@ -136,7 +136,7 @@
page: pagination.value.current, page: pagination.value.current,
size: pagination.value.pageSize, size: pagination.value.pageSize,
} }
const response = await apiRequestGet('/employees/allEmployees', params); const response = await apiRequest.get('/employees/allEmployees', params);
if (response.data.success) { if (response.data.success) {
dataSource.value = response.data.data; dataSource.value = response.data.data;

View File

@ -52,7 +52,7 @@
import { ref, reactive, onMounted } from 'vue'; import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue'; import { message } from 'ant-design-vue';
import axios from 'axios'; import axios from 'axios';
import {apiRequestGet} from '@/utils/api' import { apiRequest } from '@/utils/api'
// //
const columns = [ const columns = [
@ -100,7 +100,7 @@ const fetchData = async () => {
code: searchForm.code || undefined, code: searchForm.code || undefined,
type: searchForm.type || undefined, type: searchForm.type || undefined,
}; };
const response = await apiRequestGet('/facilities/list', params); const response = await apiRequest.get('/facilities/list', params);
if (response.data.success) { if (response.data.success) {
dataSource.value = response.data.data; dataSource.value = response.data.data;
pagination.total = response.data.total || response.data.data.length; pagination.total = response.data.total || response.data.data.length;

View File

@ -39,7 +39,7 @@
import axios from 'axios'; // HTTP import axios from 'axios'; // HTTP
import { useRouter } from 'vue-router'; // 使 Vue Router import { useRouter } from 'vue-router'; // 使 Vue Router
import { localStg } from '@/utils/storage'; import { localStg } from '@/utils/storage';
import { apiRequestPost } from '@/utils/api'; // API import { apiRequest } from '@/utils/api'; // API
const formRef = ref(); // const formRef = ref(); //
const router = useRouter(); // const router = useRouter(); //
@ -71,7 +71,7 @@
try { try {
//await formRef.value.validate(); // //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) { if (response.data.success) {
message.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 { Table as ATable, Tag as ATag } from 'ant-design-vue';
import axios from 'axios'; import axios from 'axios';
import { localStg } from '@/utils/storage'; import { localStg } from '@/utils/storage';
import { apiRequestGet } from '@/utils/api'; import { apiRequest } from '@/utils/api';
// //
const columns = [ const columns = [
{ {
@ -131,7 +131,7 @@ const fetchData = async (page = 1, pageSize = 10) => {
const token = localStg.get('token'); // token const token = localStg.get('token'); // token
try { try {
const response = await apiRequestGet('/work-orders/my-orders', const response = await apiRequest.get('/work-orders/my-orders'
// { // {
// params: { // params: {
// page: page - 1, // 0 // page: page - 1, // 0

View File

@ -37,7 +37,7 @@ import { ref, onMounted } from 'vue';
import axios from 'axios'; import axios from 'axios';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import { Tag } from 'ant-design-vue'; import { Tag } from 'ant-design-vue';
import { apiRequestGet } from '@/utils/api'; import { apiRequest } from '@/utils/api';
const columns = [ const columns = [
@ -110,7 +110,7 @@ import { apiRequestGet } from '@/utils/api';
loading.value = true; loading.value = true;
try { try {
// //
const response = await apiRequestGet("/inspection-plans/employee/my-plan") const response = await apiRequest.get("/inspection-plans/employee/my-plan")
if (response.data.success) { if (response.data.success) {
planData.value = response.data.data; planData.value = response.data.data;