common.js
// 动态测速选择的域名
// h5直接返回默认第一个域名
// vue文件用到域名的话用this.$baseURL
let domains = [
{uri:'192.168.31.215:9523', speed:0},
{uri:'api.ceshi.org', speed:0},
]
export const protocol = {
api: 'http://',//本地
// api: 'https://api.',//正式
h5Url: 'https://www.',//正式
downAPPUrl: 'https://download.'//正式
}
export async function getDomain(){
const result = new Promise((resolve, reject)=>{
testSpeed().then(res=>{
resolve(res)
}).catch(()=>{
resolve(domains[0].uri)
})
})
return result
}
// 得出最快的域名
// speedTest.jpg 需要提前放到服务器上,根据图片的访问速度来选择请求的接口
function testSpeed(){
return new Promise((resolve, reject)=>{
let array = []
domains.forEach((item, index) => {
array.push(getSpeedWithAjax(`${protocol.api}${item.uri}/images/speedTest.jpg`))
})
Promise.all(array).then(res=>{
console.log(res);
domains.forEach((e,i)=>{
e.speed = res[i]
})
let arr = sort_uris(domains)
resolve(arr[0].uri)
}).catch((err)=>{
console.log(err);
reject()
})
})
}
// 测速后排序数组
function sort_uris(array) {
let compare = function(obj1, obj2) {
var val1 = obj1.speed;
var val2 = obj2.speed;
if (val1 < val2) {
return -1;
} else if (val1 > val2) {
return 1;
} else {
return 0;
}
}
return array.filter((num) => {
return num.speed > 0;
}).sort(compare)
}
function getSpeedWithAjax(url){
return new Promise((resolve, reject) => {
let start = null;
let end = null;
start = new Date().getTime();
const xhr = uni.request({
url,
timeout:2000,
success: () => {
end = new Date().getTime();
resolve(end - start)
},
fail: () => {
resolve(0)
}
});
})
}
main.js文章来源:https://uudwc.com/A/Oq6W1
import { getDomain, protocol } from '@/utils/common.js' //公共方法
getDomain().then(domain=>{
console.log(domain);
// H5地址
let h5Url = `${protocol.h5Url}${domain}`
// APP下载地址
let downAPPUrl = `${protocol.downAPPUrl}${domain}`
// 接口
let baseUrl = `${protocol.api}${domain}`
uni.$emit('urlChange',{
baseUrl
})
Object.assign(Vue.prototype, {
'$downAPPUrl':downAPPUrl,
'$h5Url':h5Url,
'$imgUrl':baseUrl,
})
const app = new Vue({
...App,
i18n
})
app.$mount()
})
request.js文章来源地址https://uudwc.com/A/Oq6W1
let baseURL;
uni.$on('urlChange',data=>{
baseURL = data.baseUrl
})
// 这个baseURL 就是根据图片访问速度 动态获取到的接口url
console.log(baseURL)