import { isFunction } from '../is.js' import env from '@/env/index.js' const urlEnv = env === 'production' ? '' : `-${env}` const uploadUrl = `https://api-ops-yyt${urlEnv}.qniao.cn/cloud-print-user-center/utils/uploadImage` export default class Http { constructor(config = {}, { reqInterceptor, resInterceptor, transformConfig } = {}) { this.baseUrl = config.baseUrl this.header = config.header || { 'content-type': 'application/json;charset=UTF-8' } this.requestOption = config.requestOption || {} this.reqInterceptor = reqInterceptor this.resInterceptor = resInterceptor this.transformConfig = transformConfig } post(config, options) { return this.request( { method: 'POST', ...config }, options ) } get(config, options) { return this.request( { method: 'GET', ...config }, options ) } /** * @param {Object} config 和请求相关的参数 * @param {Object} options 对请求数据进行额外处理的参数 */ request(config, options) { let conf = Object.assign({}, config) const { transformConfig, reqInterceptor, resInterceptor } = this if (transformConfig && isFunction(transformConfig)) { conf = transformConfig(this, config) } let opt = Object.assign({}, this.requestOption, options) if (reqInterceptor && isFunction(reqInterceptor)) { conf = reqInterceptor(conf, opt) } return new Promise((resolve, reject) => { uni.request({ url: conf.url, data: conf.data, // enableHttpDNS: openHttpDNS && hasHttpDNSQuota && !hasSystemProxy, // httpDNSServiceId: 'wxa410372c837a5f26', timeout: conf.timeout || 5000, header: conf.header, method: conf.method, success: (res) => { let data = resInterceptor(res, opt) if (data === null) { console.log('报错的请求参数:', conf) let error = res // 组装一下错误 if (res.data && res.data.message) { error = { message: res.data.message, code:res.data.code } } reject(error) return } // 服务器错误也会用then抛出,需要自己判断data==null resolve(data) }, fail: (err) => { if (err.errno === 5) { uni.showToast({ title: '网络异常,请重新进入小程序', icon: 'none', duration: 2000 }) } // httpDNS额度用完 else if (err.errno === 602103) { // hasHttpDNSQuota = false this.request(config, options) } else { uni.showToast({ title: '服务器正在维护中,请在首页联系客服', icon: 'none', duration: 2000 }) } reject(err) } }) }).catch((err) => { // 不会再进入后面传递的then函数了 return Promise.reject(err) }) } // config:{} uploadFile(config, options) { return new Promise((resolve, reject) => { let conf = Object.assign({}, config) conf.url = uploadUrl const { reqInterceptor } = this let opt = Object.assign({}, this.requestOption, options) if (reqInterceptor && isFunction(reqInterceptor)) { conf = reqInterceptor(conf, opt) } delete conf.header['Content-Type'] uni.uploadFile({ url: conf.url, header: { ...conf.header, image: config.data.filePath // 'Content-Type': 'image/png' }, filePath: config.data.filePath, name: config.data.fileName || 'image', formData: { image: config.data.filePath }, success: (res) => { uni.hideLoading() resolve(res.data) }, fail: (err) => { reject(err) } }) }).catch((err) => { console.error('upload native err', err) }) } }