uniapp换接口
uniapp 切换接口的方法
在 uniapp 中切换接口通常涉及修改请求的基地址(baseURL)或动态切换不同环境的接口配置。以下是几种常见的方法:
配置不同环境的接口地址
在 main.js 或单独配置文件中定义不同环境的接口地址:
const apiConfig = {
dev: 'http://dev.example.com/api',
test: 'http://test.example.com/api',
prod: 'http://prod.example.com/api'
}
通过环境变量切换接口
在项目根目录创建 .env 文件:
VUE_APP_API_BASE_URL=http://dev.example.com/api
在代码中通过 process.env.VUE_APP_API_BASE_URL 获取:
const baseURL = process.env.VUE_APP_API_BASE_URL
动态切换接口地址
封装请求方法时允许动态传入 baseURL:
function request(url, data = {}, method = 'GET', baseURL = '') {
if (!baseURL) {
baseURL = uni.getStorageSync('currentAPI') || defaultBaseURL
}
return new Promise((resolve, reject) => {
uni.request({
url: baseURL + url,
method,
data,
success: resolve,
fail: reject
})
})
}
使用条件编译切换接口
在 uni-app 中可以使用条件编译针对不同平台使用不同接口:
// #ifdef H5
const baseURL = 'http://h5.example.com/api'
// #endif
// #ifdef MP-WEIXIN
const baseURL = 'http://mp.example.com/api'
// #endif
封装全局 API 管理类
创建一个 API 管理类来集中管理接口地址:
class APIManager {
constructor() {
this.currentEnv = 'dev'
this.envMap = {
dev: 'http://dev.example.com/api',
test: 'http://test.example.com/api',
prod: 'http://prod.example.com/api'
}
}
setEnv(env) {
this.currentEnv = env
}
getBaseURL() {
return this.envMap[this.currentEnv]
}
}
export default new APIManager()
注意事项
- 生产环境接口地址应该通过 HTTPS 访问
- 敏感接口地址不应直接写在代码中
- 切换接口后需要确保相关 token 或认证信息仍然有效
- 考虑添加接口切换的权限控制







