WMS_PDA/src/core/request/request.js
liufumingren 5ae92e0f63 chore(cli): 由 HBuilderX 工程迁移为 uni-app Vue2 CLI 脚手架工程
- 业务源码统一迁入 src/,H5 模板移到 public/index.html
- 新增 @vue/cli 4.5 + @dcloudio 2.0.2-5020620260917001 全套依赖与 scripts
- 保留 vue.config.js 的 ROUTES 注入(uni-simple-router 运行时依赖)
- 新增 scripts/node-compat.cjs 兼容 Node 23+ 移除的 util.isRegExp 等 API
- README 补充构建/运行/回退说明
2026-10-02 19:45:18 +08:00

176 lines
4.7 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.

/**
* Request:请求封装
* @property {Object} config = 私有属性,默认值
* @property {Function} isUrl = 私有方法,url是否完整
* @property {Function} requestBefore = 私有方法,请求前
* @property {Function} requestAfter = 私有方法,请求后
*/
import {
API_URL
} from '@/env'
export default class Request {
constructor() {
// 默认配置
this.config = {
baseUrl: API_URL,
header: {
'content-type': 'application/json',
'platform': 'pda',
'project':'warehouse'
},
url: '',
data: {},
path:'',
params: {},
method: 'GET',
dataType: 'json',
// 默认请求超时 20s,避免弱网下请求长时间挂起(真机 PDA 网络环境差异明显)
timeout: 20000,
// #ifndef MP-ALIPAY || APP-PLUS
responseType: 'text',
// #endif
custom: {},
// #ifdef APP-PLUS
sslVerify: false
// #endif
}
/* 拦截器 */
this.interceptor = {
request: cb => {
if (cb) {
this.requestBefore = cb
} else {
this.requestBefore = request => request
}
},
response: (cb) => {
if (cb) {
this.requestAfter = cb
} else {
this.requestAfter = response => response
}
}
}
}
/* 判断url是否完整 */
static isUrl(url) {
return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
}
static addQueryString(params) {
let paramsData = ''
Object.keys(params).forEach(key => {
paramsData += key + '=' + encodeURIComponent(params[key]) + '&'
})
return paramsData.substring(0, paramsData.length - 1)
}
/* 请求前 */
static requestBefore(config) {
return config
}
/* 请求后 */
static requestAfter(response) {
return response
}
/*设置全局配置*/
setConfig(func) {
return func(this.config)
}
/**
* @Function
* @param {Object} options - 请求配置项
* @prop {String} options.url - 请求路径
* @prop {Object} options.data - 请求参数
* @prop {Object} [options.responseType = config.responseType] [text|arraybuffer] - 响应的数据类型
* @prop {Object} [options.dataType = config.dataType] - 如果设为 json,会尝试对返回的数据做一次 JSON.parse
* @prop {Object} [options.header = config.header] - 请求header
* @prop {Object} [options.method = config.method] - 请求方法
* @returns {Promise<unknown>}
*/
async request(options = {}) {
options = {
...options,
...this.config,
...this.requestBefore(options)
}
return new Promise((resolve, reject) => {
let mergeUrl = Request.isUrl(options.url) ? options.url : (options.baseUrl + options.url);
let mergePath = options.path ? options.path : '';
console.log(options,mergePath,options.baseUrl);
if(mergePath){
const timestamp = Math.round(new Date() / 1000);
mergeUrl = `${options.baseUrl}?method=${mergePath}&v=1.0&timestamp=${timestamp}`
}
console.log(mergeUrl);
if (JSON.stringify(options.params) !== '{}') {
let query = Request.addQueryString(options.params);
mergeUrl += mergeUrl.indexOf('?') === -1 ? `?${query}` : `&${query}`
}
options.url = mergeUrl
// 硬超时兜底:uni.request 的 timeout 在弱网/部分安卓 WebView 下可能不触发,
// 用独立定时器保证请求 Promise 必定 settle,超时主动 abort 并走拦截器,避免界面无限卡住
const timeoutMs = Number(options.timeout) > 0 ? Number(options.timeout) : 20000;
let settled = false;
let task = null;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
if (task && typeof task.abort === 'function') {
try { task.abort(); } catch (e) {}
}
// 构造符合响应拦截器预期的结构,使 toastAfter/隐藏 loading/错误提示链路完整生效
const timeoutRes = {
errMsg: `request:fail timeout(${timeoutMs}ms)`,
statusCode: 0,
header: {},
data: { flag: 'failure', message: '网络超时,请检查网络后重试' }
};
let handled = timeoutRes;
try {
handled = this.requestAfter(timeoutRes);
} catch (e) {}
reject(handled);
}, timeoutMs + 2000);
const settle = (fn, value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
fn(value);
};
options.success = res => {
settle(resolve, this.requestAfter(res))
}
options.fail = err => {
const handled = this.requestAfter(err);
// 原生失败(超时/断网/abort)时透传原始 errMsg,便于调用方识别失败原因
settle(reject, handled === undefined || handled === null ? err : handled)
}
task = uni.request(options)
})
}
get(url, options = {}) {
return this.request({
url,
method: 'GET',
...options
})
}
post(url, data, options = {}) {
return this.request({
url,
data,
method: 'POST',
...options
})
}
}