Files
consumer-front/src/utils/request.js
T

120 lines
3.3 KiB
JavaScript
Raw Normal View History

/**
* 统一请求封装
* 自动注入 Authorization header,处理 401
* app_no 通过接口参数传递,不在 header 中
*/
import config from '@/config/env.js';
/**
* 发起请求
* @param {Object} options - uni.request 选项
* @param {string} options.url - 请求地址(可以是相对路径,会拼接 baseUrl)
* @param {string} [options.method='GET'] - 请求方法
* @param {Object} [options.data] - 请求参数
* @param {Object} [options.header] - 额外请求头
* @param {string} [options.baseUrl] - 基础地址,默认 apiBaseUrl;传 'gateway' 使用 apiGatewayUrl
* @returns {Promise<Object>} 响应数据
*/
export function request(options = {}) {
const token = uni.getStorageSync('token') || '';
// 确定 baseUrl
let baseUrl = config.apiBaseUrl;
if (options.baseUrl === 'gateway') {
baseUrl = config.apiGatewayUrl;
} else if (options.baseUrl) {
baseUrl = options.baseUrl;
}
// 拼接完整 URL
let url = options.url || '';
if (url && !url.startsWith('http')) {
url = baseUrl + url;
}
// 构建 headerapp_no 不在 header 中传,通过参数传递)
const header = {
...options.header,
};
2026-07-02 18:25:23 +08:00
// 公开接口(授权/登录/注册相关)不带 Authorization,避免 CORS 预检和 JWT 拦截
const publicPaths = [
'/api/v1/user/auth/url',
'/api/v1/user/auth/callback',
'/api/v1/user/login',
'/api/v1/user/register',
'/api/v1/user/sms/send',
];
const isPublic = publicPaths.some((p) => url.includes(p));
if (token && !isPublic) {
header['Authorization'] = `Bearer ${token}`;
}
// 开发环境请求日志
if (config.enableRequestLog) {
console.log(`[API] ${options.method || 'GET'} ${url}`, options.data || '');
console.log('[API] Headers:', header);
}
return new Promise((resolve, reject) => {
uni.request({
url,
method: options.method || 'GET',
data: options.data,
header,
timeout: config.requestTimeout,
success: (res) => {
if (config.enableRequestLog) {
console.log('[API] StatusCode:', res.statusCode);
console.log('[API] Response Headers:', res.header || res.headers);
console.log('[API] Response Body:', res.data);
}
// 401 → 清除登录状态
if (res.statusCode === 401) {
uni.removeStorageSync('token');
uni.removeStorageSync('user_info');
uni.removeStorageSync('temp_token');
}
resolve(res);
},
fail: (err) => {
if (config.enableRequestLog) {
console.error('[API] Error:', err);
}
reject(err);
},
});
});
}
/**
* GET 请求(默认走业务 API)
*/
export function get(url, data, options = {}) {
return request({ url, method: 'GET', data, ...options });
}
/**
* POST 请求(默认走业务 API)
*/
export function post(url, data, options = {}) {
return request({ url, method: 'POST', data, ...options });
}
/**
* GET 请求(走网关)
*/
export function gatewayGet(url, data, options = {}) {
return request({ url, method: 'GET', data, baseUrl: 'gateway', ...options });
}
/**
* POST 请求(走网关)
*/
export function gatewayPost(url, data, options = {}) {
return request({ url, method: 'POST', data, baseUrl: 'gateway', ...options });
}