1.環境配置 (可參考uni-官網的環境配置)
common文件夾下新建config.js
let url_config = ""
if(process.env.NODE_ENV === 'development'){
// 開發環境
url_config = 'https://*****.com/'
}else{
// 生產環境
url_config = 'https://*****.com/'
}
export default url_config
2.uni.request封裝
common文件夾下新建request.js
import urlConfig from './config.js'
const request = {}
const headers = {}
const PORT1 = '/baseinfo'
request.globalRequest = (url, method, data, power) => {
/* 權限判斷 因為有的接口請求頭可能需要添加的參數不一樣,所以這里做了區分
1 == 不通過access_token校驗的接口
2 == 文件下載接口列表
3 == 驗證碼登錄 */
switch (power){
case 1:
headers['Authorization'] = 'Basic a3N1ZGk6a3N1ZGk='
break;
case 2:
headers['Authorization'] = 'Basic a3N1ZGlfcGM6a3N1ZGlfcGM='
break;
case 3:
responseType = 'blob'
break;
default:
headers['Authorization'] = `Bearer ${
this.$store.getters.userInfo
}`
headers['TENANT-ID'] = this.$store.getters.userInfo.tenant_id
break;
}
return uni.request({
url: urlConfig + url,
method,
data: data,
dataType: 'json',
header: headers
}).then(res => {
if (res[1].data.status && res[1].data.code == 200) {
return res[1]
} else {
throw res[1].data
}
}).catch(parmas => {
switch (parmas.code) {
case 401:
uni.clearStorageSync()
break
default:
uni.showToast({
title: parmas.message,
icon: 'none'
})
return Promise.reject()
break
}
})
}
export default request
3.接口配置
項目根目錄下新建api文件,api下新建index.js
import request from '@/common/request.js'
import { formatGetUri } from '@/common/util.js'
const api = {}
const PORT1 = 'baseinfo'
// POST請求方式
api.register = params => request.globalRequest(`${PORT1}/mobile/signUp`, 'POST//必須大寫,為了兼容其他應用', params, 1)
// GET請求方式
api.register = params => request.globalRequest(`${PORT1}/mobile/signUp${formatGetUri(params)}`, 'GET //必須大寫,為了兼容其他應用',{}, 1)
export default api
4. 新建common/util.js
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
/**
* 拼接對象為請求字符串
* 對於需要編碼的文本(比如說中文)我們要進行編碼
* @param {Object} obj - 待拼接的對象
* @returns {string} - 拼接成的請求字符串
**/
export function formatGetUri(obj) {
const
params
= []
Object.keys(obj).forEach((key) => {
let
value = obj[key]
if
(
typeof
value !==
'undefined'
|| value !==
null
) {
params
.push([key, encodeURIComponent(value)].
join
(
'='
))
}
})
return
'?'
+
params
.
join
(
'&'
)
}
|
5.全局配置
在main.js中新增
import Vue from 'vue'
import App from './App'
import store from './store' // 與vue項目中配置相同,可自行配置
import request from './common/request.js'
import api from './api/index.js'
import url from './common/config.js'
Vue.config.productionTip = false
Vue.prototype.$request = request
Vue.prototype.$api = api
Vue.prototype.$url = url
App.mpType = 'app'
const app = new Vue({
...App,
store
})
app.$mount()
5.接口調用
this.$api.register({mobile: this.mobile}).then(res => {
// 獲得數據
console.log(res)
}).catch(res => {
// 失敗進行的操作
})

