uniapp app外包开发要求接口地址是可以动态修改的,首先需要一个页面,用来配置接口地址和端口。
页面代码
<template>
<view class="set-page">
<view class="set-cell">
<view class="set-cell_hd">服务器信息</view>
<view class="set-row flex-center">
<view class="flex_bd">
<view class="url">http://{{ip}} <text v-if="port">:{{port}}</text>{{pageUrl}}</view>
</view>
<view class="btn-test" @click="testLink">点击测试网络</view>
</view>
</view>
<view class="set-cell">
<view class="set-cell_hd">IP地址</view>
<view class="set-row">
<u-input v-model="ip" input-align="center" :clearable="false" />
</view>
</view>
<view class="set-cell">
<view class="set-cell_hd">端口</view>
<view class="set-row ">
<u-input v-model="port" input-align="center" :clearable="false" />
</view>
</view>
<!-- <view class="set-cell">
<view class="set-cell_hd">URL</view>
<view class="set-row ">
<u-input v-model="pageUrl" input-align="center" :clearable="false" />
</view>
</view> -->
<view class="form-footer">
<u-button throttleTime='200' @click="submit" type="primary">提交</u-button>
</view>
</view>
</template>
<script>
export default {
data() {
return {
ip: '',
port: '',
pageUrl: '',
}
},
onLoad() {
if (uni.getStorageSync('ip')) {
this.ip = uni.getStorageSync('ip')
}
if (uni.getStorageSync('port')) {
this.port = uni.getStorageSync('port')
}
},
methods: {
testLink() {
var url = 'http://' + this.ip + ':' + this.port + '/api/Comnon/Login'
uni.request({
url: url,
method: "post",
data: {},
success: (res) => {
uni.showToast({
title: '测试连接成功',
icon: 'none'
})
},
fail: (res) => {
uni.showToast({
title: '测试连接失败',
icon: 'none'
})
}
})
},
submit() {
uni.setStorageSync('ip', this.ip)
uni.setStorageSync('port', this.port)
uni.showToast({
title: '设置成功',
icon: 'none'
})
}
}
}
</script>
<style lang="scss">
.set-page {
padding: 60rpx 30rpx;
}
.set-cell {
margin-bottom: 44rpx;
.set-cell_hd {
line-height: 1;
font-weight: bold;
font-size: 14px;
line-height: 20px;
color: #000000;
margin-bottom: 24rpx;
}
}
.set-row {
/deep/ .u-input {
height: 38px;
background: #F4F6FA;
border-radius: 8px;
color: #646A73;
padding: 0 15px !important;
}
}
.set-group-row {
/deep/ .u-input {
flex: unset;
width: 62px;
padding: 0 !important;
margin-right: 10px;
}
}
.form-footer {
padding-top: 60px;
}
.btn-test {
width: 98px;
height: 26px;
background: #F4F6FA;
font-size: 12px;
line-height: 26px;
color: #4876FF;
text-align: center;
border-radius: 8px;
}
</style>
接口配置
其次是设置默认地址和端口,以及如果能够获取到缓存的地址和端口的话,则将地址和端口设置为缓存的地址和端口。
var ip = '默认ip'
var port = '默认端口'
if (uni.getStorageSync('ip')) {
ip = uni.getStorageSync('ip')
}
if (uni.getStorageSync('port')) {
port = uni.getStorageSync('port')
}
var url = 'http://' + ip + ':' + port
var configs = {
baseUrl: url,
baseUrl2: url,
throttleTime: 3000,
debounceTime: 500,
uploadImage: url + '/api/Command/UpLoadImg',
upload2: url + '/api/common/upload'
}
export default configs