uniapp:配置动态接口域名,根据图片访问速度,选择最快的接口

文章介绍了如何在UniApp项目中,通过使用`network-speed-test`库和uni.request进行服务器图片加载速度测试,对节点进行排序,并展示了一个示例代码片段,展示了如何获取并处理响应时间和速度计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先上源码看效果,新建的uniapp项目,已测H5,APP可直接使用

1、node.vue

<template>
	<view class="index">
		<view class="header df-aic-jusb">
			<text class="fsz-26 color-9">节点速度</text>
			<view class=" df-aic">
				<view class="bor ac1"></view>
				<view class="fsz-22 color-6"></view>
				<view class="bor ac2"></view>
				<view class="fsz-22 color-6"></view>
				<view class="bor ac3"></view>
				<view class="fsz-22 color-6"></view>
			</view>
		</view>
		<view class="list">
			<view class="item df-aic-jusb" v-for="(item,index) in sort_uris" :key="index" @click="change(item,index)">
				<view class="df-aic">
					<image src="../../static/1.png" mode="" v-if="item.active == 1"></image>
					<text>{{item.name}}</text>
				</view>
				<view class="df-aic">
					<view>{{item.speed}}ms</view>
					<view class="bor ac1" v-if="Number(item.speed) < 200"></view>
					<view class="bor ac2" v-if="Number(item.speed) >= 200 && Number(item.speed) <500"></view>
					<view class="bor ac3" v-if="Number(item.speed) >= 500"></view>
				</view>
			</view>
		</view>
		<view class="btn df-aic-jucen" @click="testSpeed()">
			<image src="../../static/2.png" mode=""></image>
			<text>确认</text>
		</view>

	</view>
</template>

<script>
	import {
		getSpeedWithImg,
		getSpeedWithAjax
	} from 'network-speed-test';
	import BigNumber from "bignumber.js";
	export default {
		name: 'node',
		data() {
			return {
				protocol: {
					api: 'https://api.',
				},
				uris: [],
			}
		},
		computed: {
			// 根据访问时间,重新排序
			sort_uris: function() {
				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 this.uris.filter((num) => {
					return num.speed > 0;
				}).sort(compare)
			}
		},
		async onLoad(option) {
			if(this.protocol.api == 'https://api.'){
				// 正式接口
				this.uris = [
					{
						"name": "节点 1",
						"domain": "***.com",
						active:0
					},
					{
						"name": "节点 2",
						"domain": "***.cn",
						active:0
					},
					{
						"name": "节点 3",
						"domain": "***.net",
						active:0
					},
					{
						"name": "节点 4",
						"domain": "***.org",
						active:0
					},
				]
			}
			await this.testSpeed() // 1、访问服务器的图片,进行测速
			let baseUrl = uni.getStorageSync('baseUrl')
			console.log('默认地址:',baseUrl);
			if(baseUrl){ // 2、如果有默认地址,就设置高亮显示
				this.uris.forEach((item,index)=>{
					if(this.protocol.api +item.domain === baseUrl){
						item.active = 1
					}
				})
			}
		},
		methods: {
			async testSpeed() {
				this.uris.forEach((item, index) => {
					getSpeedWithAjax(this.protocol.api + item.domain + '/images/speedTest.jpg?time=' + Date.now(),
						'5.3').then(res => {
						this.$set(item, 'speed', new BigNumber(res).dp(0).toNumber())
					})
				})
			},
			change(item) {
				uni.showLoading({
					title: '',
					mask:true,
				});
				if(item.speed >= 999){
					uni.hideLoading()
					this.$toast('Network Timeout')
					return
				}
				this.uris.forEach((item,index)=>{
					item.active = 0
				})
				console.log(item);
				item.active = 1;
				// 接口地址
				let baseUrl = `${this.protocol.api}${item.domain}`
				uni.setStorageSync('baseUrl', baseUrl)
				setTimeout(()=>{
					uni.hideLoading()
					uni.navigateTo({
						url: '/pages/index/index',
					})
				},1000)
			}
		}
	}
</script>

<style lang="scss">
	.index {
		.df-aic{
			display: flex;
			align-items: center;
		}
		.df-aic-jucen{
			display: flex;
			align-items: center;
			justify-content: center;
		}
		.df-aic-jusb{
			display: flex;
			align-items: center;
			justify-content: space-between;
		}
		.bor {
			width: 8rpx;
			height: 8rpx;
			border-radius: 50%;
			margin: 0 14rpx 0 30rpx;
		}

		.ac1 {
			background: #37DD7D;
		}

		.ac2 {
			background: #F2B914;
		}

		.ac3 {
			background: #EC2A13;
		}

		.header {
			width: 690rpx;
			height: 88rpx;
			background: #f5f5f5;
			border-radius: 30rpx;
			margin: 30rpx auto 20rpx;
			padding: 0 30rpx;
		}

		.list {
			width: 690rpx;
			background: #f5f5f5;
			border-radius: 30rpx;
			margin: auto;
			padding: 0 30rpx;

			.item {
				height: 83rpx;
				border-bottom: 1px solid #EEEEEE;

				uni-image {
					width: 20rpx;
					height: 20rpx;
					margin-right: 10rpx;
				}
			}
		}

		.btn {
			width: 690rpx;
			height: 100rpx;
			background: #FCD436;
			border-radius: 20rpx;
			margin: 130rpx auto;
			color: #000;
			uni-image {
				width: 30rpx;
				height: 30rpx;
				margin-right: 10rpx;
			}

			uni-text {
				font-size: 26rpx;
				color: #000;
			}
		}
	}
</style>

2、index.vue

<template>
	<view class="content">
		<view class="text-area" @click="node">
			<text class="title">选择节点</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {

			}
		},
		onShow() {
			let baseUrl = uni.getStorageSync('baseUrl')
			console.log('当前节点:',baseUrl);
			uni.request({
				url: baseUrl + '/api/notices/pop',
				data: {},
				header: {},
				method: 'GET',
				success: (res) => {
					console.log(res);
				},
			});
		},
		methods: {
			node(){
				uni.navigateTo({url: '/pages/index/node'})
			},
		}
	}
</script>

实现步骤:

npm install network-speed-test@1.0.1
npm install bignumber.js

node_modules/network-speed-test文件内的client.js文件,只修改getSpeedWithAjax方法里的代码,替换为uniapp的接口请求方式

function getSpeedWithAjax(url) {
    // return new Promise((resolve, reject) => {
    //     let start = null;
    //     let end = null;
    //     start = new Date().getTime();
    //     const xhr = new XMLHttpRequest();
    //     xhr.onreadystatechange = function () {
    //         if (xhr.readyState === 4) {
    //             end = new Date().getTime();
    //             const size = xhr.getResponseHeader('Content-Length') / 1024;
    //             const speed = size * 1000 / (end - start)
    //             resolve(speed);
    //         }
    //     }
    //     xhr.open('GET', url);
    //     xhr.send();
    // }).catch(err => { throw err });
	
	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(999)
			}
		});
	})
}

完成效果:通过访问服务器的图片,计算加载速度,重新排序。代码中的/images/speedTest.jpg先随便找个图片放到服务器上。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值