https://www.cnblogs.com/gqx-html/p/10967570.html
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_idbreak;}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 | /** * 拼接对象为请求字符串 * 对于需要编码的文本&#xff08;比如说中文&#xff09;我们要进行编码 * &#64;param {Object} obj - 待拼接的对象 * &#64;returns {string} - 拼接成的请求字符串 **/ export function formatGetUri(obj: Object) { const params : Array< string > &#61; [] Object.keys(obj).forEach((key) &#61;> { let value &#61; obj[key] if ( typeof value !&#61;&#61; &#39;undefined&#39; || value !&#61;&#61; null ) { params .push([key, encodeURIComponent(value)]. join ( &#39;&#61;&#39; )) } }) return &#39;?&#39; &#43; params . join ( &#39;&&#39; ) } |
5.全局配置
在main.js中新增
import Vue from &#39;vue&#39;
import App from &#39;./App&#39;
import store from &#39;./store&#39; // 与vue项目中配置相同&#xff0c;可自行配置import request from &#39;./common/request.js&#39;
import api from &#39;./api/index.js&#39;
import url from &#39;./common/config.js&#39;Vue.config.productionTip &#61; false
Vue.prototype.$request &#61; request
Vue.prototype.$api &#61; api
Vue.prototype.$url &#61; urlApp.mpType &#61; &#39;app&#39;const app &#61; new Vue({...App,store
})app.$mount()
5.接口调用
this.$api.register({mobile: this.mobile}).then(res &#61;> {// 获得数据 console.log(res)
}).catch(res &#61;> {// 失败进行的操作
})