uiapp请求方法封装
// 请求接口 const commoneUrl = "http://xxxxxxxxxx.com/"; // new 域名 //get请求封装 function getRequest(url, data) { var promise = new Promise((resolve, reject) => { var postData = data; uni.request({ url: commoneUrl + url, data: postData, method: "GET", dataType: 'json', header: { 'content-type': 'application/json' }, success: function(res) { if (res.statusCode === 200) { resolve(res.data); } else { resolve(res.data) } }, error: function(e) { reject('网络出错'); } }); }); return promise; } //post请求封装 function postRequest(url, data) { var promise = new Promise((resolve, reject) => { var postData = data; uni.request({ url: commoneUrl + url, data: postData, method: 'POST', // withCredentials:true, header: { 'content-type': 'application/x-www-form-urlencoded', // "Authorization":'22' }, success: function(res) { // console.log(res); if (res.statusCode === 200 && res.data.resultCode == 0) { resolve(res.data); } else { resolve(res.data) } }, error: function(e) { reject('网络出错'); } }) }); return promise; } //post请求封装 function postHeaderRequest(url, data) { var promise = new Promise((resolve, reject) => { var postData = data; uni.request({ url: commoneUrl + url, data: postData, method: 'POST', header: { 'content-type': 'application/json', 'Authorization': 'Bearer ' + postHeader }, success: function(res) { if (res.statusCode === 200 && res.data.resultCode == 0) { resolve(res.data); } else { resolve(res.data) } }, error: function(e) { reject('网络出错'); } }) }); return promise; } module.exports = { postRequest, postHeaderRequest, getRequest, commoneUrl }
mian.js全局挂载
// 请求方法 import http from './utils/request.js' Vue.prototype.$http = http
页面调用 举例
// 收藏 collectFun() { let id = this.shopInfo.goods_id const url = 'Goods/collect_goods'; let bodyParam = { openid: this.$store.state.openid, goods_id: id } this.$http.postRequest(url, bodyParam).then(res => { // console.log(res); if (res.status === 1) { this.$uti.total(res.msg) this.shopBox(id) } if (res.status === 2) { this.$uti.total(res.msg) this.shopBox(id) } }) },