uniapp接口封装

第一步:新建common.js

// 公共变量
const base_url = 'http://xxxxx/'
const httpRequest = (opts, data) => {
let httpDefaultOpts = {
url: base_url + opts.url,
data: data,
beforeSend :function(xmlHttp){
xmlHttp.setRequestHeader("If-Modified-Since","0");
xmlHttp.setRequestHeader("Cache-Control","no-cache");
},
method: opts.method,
header: opts.method == 'GET' ? {
'X-Requested-With': 'XMLHttpRequest',
"Accept": "application/json",
"Content-Type": "application/json; charset=UTF-8"
} : {
'content-type': 'application/x-www-form-urlencoded',
"token": uni.getStorageSync("token")
},
dataType: 'json',
}
let promise = new Promise(function(resolve, reject) {
uni.request(httpDefaultOpts).then(
(res) => {
resolve(res[1])
}
).catch(
(response) => {
reject(response)
}
)
})
return promise
};
export default {
base_url,
httpRequest
}

第二步:方法调用

1,在要使用的页面引入import request from "../../static/common.js"

2,使用

request.httpRequest({
url:'api/index/addreport',
method: 'POST',
},{
activity_id: that.activity_id, //活动ID
reporttype_id: that.report_id,
content: that.reportname
}).then(
res=>{
if(res.data.code==1){
uni.showToast({
title:"举报成功,感谢您的反馈!",
icon:"none",
duration:2000
})
}else{
uni.showToast({
title:res.data.msg,
icon:"none",
duration:2000
})
}
},error=>{
return
}
)}

..
原文地址:https://www.cnblogs.com/shoolnight/p/14809900.html