一、uniapp
在uni-app中配置小程序的接口地址,可以按照以下步骤进行:
1.在uni-app项目的根目录下创建一个名为 config.js的文件,并确保文件的后缀是 .js。在 config.js文件中定义不同运行环境下的接口地址。例如:
const apiConfig = {develop: {api_host: "http://localhost:3000",},trial: {api_host: "https://api-trial.example.com",},release: {api_host: "https://api.example.com",},
};export default apiConfig;
在上述示例中,我们定义了三个运行环境下的接口地址:开发版、体验版和正式版 。
2.在uni-app项目的 main.js文件中引入 config.js文件,如:import apiConfig from './config.js’。在 main.js文件中根据当前小程序的运行环境选择对应的接口地址,并将其挂载到Vue原型上。例如:
import Vue from 'vue'
import App from './App'import apiConfig from './config.js'Vue.prototype.$apiHost = ''// 获取当前帐号信息
const accountInfo = uni.getAccountInfoSync();
const envVersion = accountInfo.miniProgram.envVersion;if (envVersion === 'develop') {Vue.prototype.$apiHost = apiConfig.develop.api_host;
} else if (envVersion === 'trial') {Vue.prototype.$apiHost = apiConfig.trial.api_host;
} else if (envVersion === 'release') {Vue.prototype.$apiHost = apiConfig.release.api_host;
}Vue.config.productionTip = falseApp.mpType = 'app'const app = new Vue({...App
})
app.$mount()
在上述示例中,我们通过获取小程序的运行环境版本 envVersion,根据 apiConfig中定义的接口地址选择对应的 a p i H o s t 。然后,将 apiHost。然后,将 apiHost。然后,将apiHost挂载到Vue原型上,以便在整个应用程序中使用。
3.在需要使用接口地址的组件或页面中,可以通过 this.$apiHost来获取当前的接口地址。例如:
<template><view><text>{{ $apiHost }}/api/endpoint</text></view>
</template><script>
export default {mounted() {console.log(this.$apiHost); // 输出当前接口地址}
}
</script>
在上述示例中,我们在模板中使用了 {{ $apiHost }}/api/endpoint来显示当前的接口地址,并在 mounted钩子函数中打印了当前接口地址。
这样,根据不同的小程序运行环境,你可以区分使用不同的接口地址,并在uni-app中的组件或页面中使用。
二、微信小程序
在微信小程序中,可以使用全局配置和使用开发、体验、生产环境的地址。以下是在其他页面中使用地址的代码编写方式:
1. 在小程序的全局配置文件 app.js 中,定义全局变量来存储地址信息。例如:
App({globalData: {apiHost: ""},onLaunch: function() {// 获取当前帐号信息const accountInfo = wx.getAccountInfoSync();const envVersion = accountInfo.miniProgram.envVersion;let apiHost = "";if (envVersion === "develop") {apiHost = "http://localhost:3000";} else if (envVersion === "trial") {apiHost = "https://api-trial.example.com";} else if (envVersion === "release") {apiHost = "https://api.example.com";}this.globalData.apiHost = apiHost;}
})
在上述示例中,我们定义了三个运行环境下的配置项:开发版、体验版和正式版,包括了接口地址等。
2. 在其他页面中,可以通过 getApp() 方法获取全局变量,并使用其中存储的地址信息。例如:
const app = getApp();
const apiHost = app.globalData.apiHost;// 在其他页面中使用apiHost构建请求URL并发送请求
const url = `${apiHost}/api/endpoint`;
wx.request({url: url,method: 'GET',success: function(res) {console.log(res.data);},fail: function(error) {console.error(error);}
});