Files
inkreach-uni/api/request.js
T
2026-08-22 19:05:26 +08:00

70 lines
2.3 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 BASE_URL = 'https://official.inkreach.cc/api/';
export { BASE_URL };
// 默认配置
const TIMEOUT = 30000;
const DEFAULT_HEADER = { 'Content-Type': 'application/json' };
// 统一拼装 URL:完整地址直接返回,否则 BASE_URL + path
// 图片/静态资源路径也可直接调用,得到完整可访问地址
export function buildUrl(url) {
if (!url) return '';
if (/^https?:\/\//i.test(url)) return url;
const base = BASE_URL.replace(/\/+$/, '');
const path = 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;