// httpService.js 对 uni.request 的封装。
在数据请求入口处,统一先进行 域名获取,即 执行 config.requestRemoteIp 方法
import config from '@/config'
import Vue from 'vue'
import cacheData from '@/service/cacheData.js'
const MockUtil = () => import('@/libs/mockUtil.js')
import Storage from '@/libs/storage.js'
class HttpRequest {
/**
* 读取接口数据
* @param options 请求信息
* @param noMock 在整体使用mock数据的情形下,可 单独设置 某个接口请求真实数据
* @param cacheId
* @returns {*}
*/
async requestResolve(options, urlCustom = '', noMock = false, cacheId = null) {
let remoteIP = await config.requestRemoteIp(); // 动态设置接口请求域名
if (process.env.NODE_ENV === 'development' && config.isMockApi && !noMock) {
return this.getMockData(options)
}
if (cacheId && cacheData[cacheId]) {
return this.testHttp(cacheData[cacheId])
}
return new Promise((resolve, reject) => {
let baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro;
options.url = baseUrl + options.url + `${urlCustom}`;
uni.request(
Object.assign({
success: (res) => {
if (res.statusCode != '200'){
uni.showToast({
title: '服务器错误:'+res.statusCode,
icon: "none"
})
reject()
}
else if (res.data.code == 10001) {
Storage.removeToken();
let vue = new Vue();
vue.$store.dispatch('logout')
vue.$routeUtil.reLaunch('main');
}
else if (res.data.code != 200) {
if (res.data.message) {
uni.showToast({
icon: 'none',
title: res.data.message
});
}
reject(res.data)
} else {
if (cacheId) {
cacheData[cacheId] = res.data.data
}
resolve(res.data.data)
}
},
fail: err => {
uni.showToast({
title: '服务器错误',
icon: "none"
})
}
}, options)
);
})
}
/**
* mock数据按需导入
* @param options
* @returns {*}
*/
async getMockData(options) {
const Mock = await MockUtil()
const MockUrl = Mock.default[options.url]
if (typeof MockUrl !== 'function') {
return this.testHttp(MockUrl)
}
if (options.method === 'post') {
return this.testHttp(MockUrl(options.data, false))
}
return this.testHttp(MockUrl(options.params, true))
}
testHttp(data) {
let pro = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(data)
}, 50)
})
return pro
}
}
export default new HttpRequest()
// config.js
const config = {
isMockApi: false,
// requestUrl: 'http://qiniu.eightyin.cn/teacherpath.json?time=' + Math.random().toString(36),
requestUrl: 'http://qiniu.eightyin.cn/teacherpathtest.json?time=' + Math.random().toString(36),
baseUrl: {
dev: '',
pro: ''
},
img: {
ossDomain: ''
},
uuid: Math.random().toString(36).substring(3, 20),
requestRemoteIp: () => {
console.log('config:', config)
if (config.RemoteIpInited)
return Promise.resolve();
return new Promise((resolve, reject) => {
uni.request({
url: config.requestUrl,
success: (response) => {
//todo 测试
// config.baseUrl.pro = response.data.data.path;
config.baseUrl.dev = 'http://bayin5.mycwgs.com/';
config.img.ossDomain = response.data.data.ossDomain;
config.RemoteIpInited = true;
resolve()
},
fail: () => {
config.RemoteIpInited = true;
resolve()
}
})
});
}
}
export default config
版权声明:本文为aliyun3原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。