文章参考 https://www.cnblogs.com/easth/p/uniapp_http.html
在项目中新建common文件夹,新建文件http.js
module.exports = (params) => {
let url = params.url;
let method = params.method;
let header = params.header || {};
let data = params.data || {};
let token = 'Bearer ' + getApp().globalData.token
// 请求方式 GET POST
if (method) {
method = method.toUpperCase(); // 小写转大写
if (method == "POST") {
header = {
'Authorization': token,
'content-type': 'application/x-www-form-urlencoded'
}
} else {
header = {
'Authorization': token,
}
}
}
// 发起请求 加载动画
if (!params.hideLoading) {
uni.showLoading({
title: "加载中"
})
}
// 发起网络请求
uni.request({
url: url,
method: method || "GET",
header: header,
data: data,
dataType: "json",
sslVerify: false, // 是否验证ssl证书
success: res => {
if (res.statusCode && res.statusCode != 200) {
// api错误
uni.showModal({
content: res.msg
})
return;
}
typeof params.success == "function" && params.success(res);
},
fail: err => {
uni.showModal({
content: err.msg
})
typeof params.fail == "function" && params.fail(err);
},
complete: (e) => {
console.log("请求完成");
uni.hideLoading()
typeof params.complete == "function" && params.complete(e);
return;
}
})
}
然后在main.js中全局注册
import Vue from 'vue'
import App from './App'
Vue.config.productionTip = false
import uView from 'uview-ui';
import http from './common/http.js'
Vue.prototype.http=http
Vue.use(uView);
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
后面就可以直接在页面中用了
getList() {
let str = JSON.stringify({ activityId: 1 });
let id = base64.encode(str);
let that = this;
that.http({
url: '/activityLuckDraw/activity/' + id,
success(res) {
console.log(res)
if(res.data.statusCode == 404){
that.show=true
that.content=res.data.statusDescription
return
}
let obj = res.data.object.activity;
if(obj.activityDetail.substr(0,1) == "["){
that.list2 = JSON.parse(obj.activityDetail);
}
if(obj.activityRule.substr(0,1) == "["){
that.list4 = JSON.parse(obj.activityRule);
}
obj.pools[0].index=0
obj.pools[1].index=1
obj.pools[2].index=2
obj.pools[3].index=7
obj.pools[4].index=3
obj.pools[5].index=6
obj.pools[6].index=5
obj.pools[7].index=4
obj.pools.splice(4,0,{})
that.list3=obj.pools
obj.brandIntroduction = JSON.parse(obj.brandIntroduction);
console.log(obj);
obj.setPrice =that.toDecimal2(obj.setPrice)
that.obj = obj;
getApp().globalData.submitField=that.obj.submitField
getApp().globalData.arrays=that.obj.arrays
getApp().globalData.details=that.obj.details
that.showTimes();
},
fail(err) {
console.log(err);
}
});
},
```