package.json文件追加配置壞境
注意:若項目之前未使用npm管理依賴(項目根目錄下無package.json文件),先在項目根目錄執(zhí)行命令初始化npm工程:
npm init -y
官網(wǎng)說明:https://uniapp.dcloud.io/frame?id=npm%E6%94%AF%E6%8C%81
//package.json追加配置環(huán)境
"uni-app" : {
"scripts" : {
"build:test" : { //名稱
"title" : "build:test",
"env" : {
"UNI_PLATFORM" : "h5",
"VUE_APP_BASE_URL":"http://130.0.0.146:8080"
}
},
"build:pro" : { //名稱
"title" : "build:pro",
"env" : {
"UNI_PLATFORM" : "h5",
"VUE_APP_BASE_URL":"http://120.0.4.37:8080"
}
}
}
}
官網(wǎng)說明:https://uniapp.dcloud.io/collocation/package
對應(yīng)Hbuild工具欄發(fā)行菜單追加了打包環(huán)境,如下圖所示:

image.png
應(yīng)用
import Vue from 'vue'
import store from '@/store'
export default {
common:{
//本地運行是獲取不到【VUE_APP_BASE_URL 】,默認使用【http://1330.0.4.37:8080】
baseUrl:process.env.VUE_APP_BASE_URL || 'http://1330.0.4.37:8080',
data:{},
method:'GET',
dataType:'json',
responseType:'',
},
request(options={}){
let header = {
'Content-Type':'application/json;charset=UTF-8',
'Authorization':'Bearer '+ uni.getStorageSync('token'),
'Accept-Language':'zh-CN'
}
options.url = this.common.baseUrl+'' + options.url
options.header = {...header,...options.header}
options.data = options.data || this.common.data
options.method = options.method || this.common.method
options.dataType = options.dataType || this.common.dataType
options.responseType=options.responseType || this.common.responseType
console.log('打包部署測試服后,會獲取測試環(huán)境地址')
console.log(process.env.VUE_APP_BASE_URL)
return new Promise((res,rej)=>{
uni.request({
...options,
success: (result) => {
let data = result.data
res(data)
},
fail: (error) => {
console.log('error----------------')
console.log(error)
let message = error.errMsg;
if (message == "Network Error") {
message = "后端接口連接異常";
}
else if (message == 'request:fail timeout') {
message = "系統(tǒng)接口請求超時";
}
uni.showToast({
title: message || '請求失敗',
duration: 1000,
icon:'none'
});
return rej()
},
complete: (e) => {
uni.hideLoading();
}
})
})
},
get(url,data={},options={}){
options.url = url
options.data = data
options.method = 'GET'
return this.request(options)
},
post(url,data={},options={}){
options.url = url
options.data = data
options.method = 'POST'
return this.request(options)
},
put(url,data={},options={}){
options.url = url
options.data = data
options.method = 'PUT'
return this.request(options)
},
del(url,data={},options={}){
options.url = url
options.data = data
options.method = 'DEL'
return this.request(options)
}
}