在pages同层文件夹中建一个service的文件夹,再建立一个http.js的文件,以下是http.js代码
// 项目请求中业务域名
var rootDocment =
'http://devwx.golfgreenshow.com/';
//
http头部文件,可以根据个人需要进行修改
var header = {
'Accept':
'application/json',
'content-type':
'application/json',
'Authorization':
null,
}
//get请求文件
function getReq(url,data,cb) {
wx.showLoading({
title:
'加载中',
})
wx.request({
url: rootDocment + url,
method:
'get',
data: data,
header: header,
success:
function (res) {
wx.hideLoading();
return
typeof cb ==
"function" && cb(res.data)
},
fail:
function () {
wx.hideLoading();
wx.showModal({
title:
'网络错误',
content:
'网络出错,请刷新重试',
showCancel:
false
})
return
typeof cb ==
"function" && cb(
false)
}
})
}
//post请求
function postReq(url, data, cb) {
wx.showLoading({
title:
'加载中',
})
wx.request({
url: rootDocment + url,
header: header,
data: data,
method:
'post',
success:
function (res) {
wx.hideLoading();
return
typeof cb ==
"function" && cb(res.data)
},
fail:
function () {
wx.hideLoading();
wx.showModal({
title:
'网络错误',
content:
'网络出错,请刷新重试',
showCancel:
false
})
return
typeof cb ==
"function" && cb(
false)
}
})
}
//最后别忘了抛出来
module.exports = {
getReq: getReq,
postReq: postReq,
header: header,
}
上面的文件建立好之后使用方法:
在当前使用的js文件中引入该http.js
var http =
require(
'../../../service/http.js');
// 新闻详情
getNewsBulletin:
function () {
var that =
this;
http.getReq(
"api5/News/" + that.data.detailID +
'?option=event',{},
function (res) {
that.setData({
newDetails: res.data
})
})
},