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

133 lines
3.1 KiB
JavaScript

// 统一请求处理
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
});
// 解析响应数据
const data = await response.json();
// 处理 401 未授权
if (response.status === 401) {
// 检查是否是认证失败(如用户名密码错误)
if (data.code === 401 && data.message) {
throw new Error(data.message);
}
// 其他 401 情况(如 token 过期)
clearAuth()
// 避免重复导航
if (router.currentRoute.path !== '/login') {
router.push('/login')
}
throw new Error('登录已过期,请重新登录')
}
// 根据后端统一响应格式处理
// 成功响应: { code: 200, message: 'xxx', data: xxx }
if (data.code === 200) {
return data;
}
// 业务错误(如参数错误、权限不足等)
// 后端格式: { code: 400/403/404/500, message: 'xxx', data: null }
const errorMessage = data.message || '操作失败';
throw new Error(errorMessage);
} 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
};