Files
inkreach-uni/api/request.js
T
2026-08-31 17:37:32 +08:00

76 lines
2.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* uni-app 简易请求封装
* - 统一拼接 BASE_URL + path
* - 注入 token header
* - Promise 化,提供 get/post/put/delete 快捷方法
*
* 用法:
* import request from '@/api/request.js'
* request.get('/user/info', { id: 1 })
* request.post('/user/login', { username, password })
*/
// 基础路径:修改此处即可切换后端地址
// 所有端统一直连后端
const DOMAIN = 'https://official.inkreach.cc';
// 接口走 v2 环境
const BASE_URL = DOMAIN + '/v2-api/';
// 静态资源直挂域名根目录(如 /assets/miniprogram/...),不拼接 v2-api
const ASSET_BASE = DOMAIN + '/';
export { BASE_URL, ASSET_BASE };
// 默认配置
const TIMEOUT = 30000;
const DEFAULT_HEADER = { 'Content-Type': 'application/json' };
// 统一拼装 URL:完整地址直接返回,否则 BASE_URL + path
// /assets/ 开头的静态资源路径用域名根目录拼接(不拼 v2-api)
export function buildUrl(url) {
if (!url) return '';
if (/^https?:\/\//i.test(url)) return url;
const path = url.replace(/^\/+/, '');
if (path.startsWith('assets/')) return ASSET_BASE + path;
const base = BASE_URL.replace(/\/+$/, '');
return path ? `${base}/${path}` : base;
}
// 统一取 header(注入 token
function buildHeader(extraHeader) {
const header = Object.assign({}, DEFAULT_HEADER, extraHeader || {});
const token = uni.getStorageSync('token');
if (token) header['Authorization'] = `Bearer ${token}`;
return header;
}
/**
* 核心请求方法
* @param {Object} options
* @param {string} options.url 相对路径或完整 URL
* @param {string} [options.method='GET']
* @param {Object} [options.data] 请求参数 / body
* @param {Object} [options.header] 额外 header
* @returns {Promise<any>}
*/
function request(options = {}) {
return new Promise((resolve, reject) => {
uni.request({
url: buildUrl(options.url || ''),
method: (options.method || 'GET').toUpperCase(),
data: options.data || {},
header: buildHeader(options.header),
timeout: TIMEOUT,
dataType: 'json',
success: resolve,
fail: reject
});
});
}
// 快捷方法
request.get = (url, data, options) => request({ url, method: 'GET', data, ...options });
request.post = (url, data, options) => request({ url, method: 'POST', data, ...options });
request.put = (url, data, options) => request({ url, method: 'PUT', data, ...options });
request.delete = (url, data, options) => request({ url, method: 'DELETE', data, ...options });
export default request;