背景
接口域名没有写死,而是动态获取。具体实现就是 通过读取一个静态json文件,来设置真实的接口域名。好处是原域名有可能被封,这样可以直接后台操作修改该配置文件即可;不然的话,h5 项目可能还好说,app 的话必须重新发版。
代码
// 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 {
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)
);
})
}
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
以上就是分析uniapp如何动态获取接口域名的详细内容,更多关于uniapp动态获取接口域名的资料请关注编程网其它相关文章!