86 lines
3.0 KiB
JavaScript
86 lines
3.0 KiB
JavaScript
/**
|
||
* 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 })
|
||
*/
|
||
|
||
// 基础路径:修改此处即可切换后端地址
|
||
// #ifdef H5
|
||
// H5 端走 devServer 代理(manifest.json h5.devServer.proxy),规避浏览器 CORS 限制
|
||
const BASE_URL = '/';
|
||
// #endif
|
||
// #ifndef H5
|
||
// 小程序端直连后端 v2 环境
|
||
const BASE_URL = 'https://official.inkreach.cc/v2-api/';
|
||
// #endif
|
||
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(/^\/+/, '');
|
||
let full = path ? `${base}/${path}` : base;
|
||
// #ifdef H5
|
||
// uni-app H5 的 image 组件会将以 / 开头的路径重写为 routerBase + path
|
||
// (如 /assets/x.png → /h5/assets/x.png),导致 devServer 代理匹配不到而 404。
|
||
// 这里拼成完整绝对地址(https://host/assets/x.png),image 组件对 http(s):// 开头的路径原样放行
|
||
if (typeof window !== 'undefined' && full.charAt(0) === '/') {
|
||
full = window.location.origin + full;
|
||
}
|
||
// #endif
|
||
return full;
|
||
}
|
||
|
||
// 统一取 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;
|