rentease-web-new/src/api/request.js

125 lines
2.8 KiB
JavaScript
Raw Normal View History

2026-04-20 06:44:41 +00:00
// 统一请求处理
import { getToken, isTokenExpired, clearAuth, getTenantId } from '@/utils/auth'
import router from '@/router'
const API_BASE_URL = process.env.VUE_APP_API_BASE_URL || '/api';
// 不需要认证的接口列表
const publicUrls = [
'/auth/login',
'/auth/register-tenant'
]
// 检查是否为公开接口
function isPublicUrl(url) {
return publicUrls.some(publicUrl => url.includes(publicUrl))
}
// 通用请求函数
export async function request(url, options = {}) {
try {
const isPublic = isPublicUrl(url)
// 检查 Token 是否过期(公开接口跳过)
if (!isPublic && isTokenExpired()) {
clearAuth()
// 避免重复导航
if (router.currentRoute.path !== '/login') {
router.push('/login')
}
throw new Error('登录已过期,请重新登录')
}
// 获取 Token 和租户ID并添加到请求头
const token = getToken()
const tenantId = getTenantId()
const headers = {
'Content-Type': 'application/json',
...options.headers
}
if (token) {
headers['Authorization'] = `Bearer ${token}`
}
if (tenantId) {
headers['X-Tenant-Id'] = tenantId
}
const response = await fetch(`${API_BASE_URL}${url}`, {
...options,
headers
});
// 处理 401 未授权
if (response.status === 401) {
const errorData = await response.json();
// 检查是否是认证失败(如用户名密码错误)
if (errorData.code === 401 && errorData.message) {
throw new Error(errorData.message);
}
// 其他 401 情况(如 token 过期)
clearAuth()
// 避免重复导航
if (router.currentRoute.path !== '/login') {
router.push('/login')
}
throw new Error('登录已过期,请重新登录')
}
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('API request error:', error);
throw error;
}
}
// GET 请求
export function get(url, params = {}) {
const queryString = Object.entries(params)
.filter(([key, value]) => value !== undefined && value !== null && value !== '')
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
const fullUrl = queryString ? `${url}?${queryString}` : url;
return request(fullUrl, {
method: 'GET'
});
}
// POST 请求
export function post(url, data = {}) {
return request(url, {
method: 'POST',
body: JSON.stringify(data)
});
}
// PUT 请求
export function put(url, data = {}) {
return request(url, {
method: 'PUT',
body: JSON.stringify(data)
});
}
// DELETE 请求
export function del(url) {
return request(url, {
method: 'DELETE'
});
}
export default {
get,
post,
put,
delete: del,
request
};