先在utils文件夹下创建http.js文件,在此文件中封装请求
上代码
export default class Http{
request(url,data=[],method){
let header = {}
let token = wx.getStorageSync('token')
let openid = wx.getStorageSync('openid')
if(token){
header.token = token
}
if(openid){
header.openid = openid
}
//域名/路由 可以封装起来 这里为了展示没有进行封装
url = `http://www.xxx.com/${url}`
return new Promise(function(resolve,reject){
wx.request({
url,
data,
header,
method,
dataType:'json',
success:(res)=>{
if(res.statusCode !== 200){
if(res.data.msg){
wx.showModal({
content: res.data.msg,
showCancel: false
})
}else{
wx.showModal({
content: '网络连接断开,请稍后重试',
showCancel: false
})
}
return
}
resolve(res.data)
},
fail:(ret)=>{
wx.showModal({
content: '网络连接断开,请稍后重试',
showCancel: false
})
}
})
})
}
}
页面js调用
import Http from "../../utils/http"
let http = new Http
Page({
/**
* 页面的初始数据
*/
data: {
slideshow: [],
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.getSlideshow();
},
getSlideshow() {
//http.request(url,data,method)
http.request('/api/slideshow').then((res) => {
this.setData({
slideshow: res
})
})
}
})
本章还有待完善出,可根据个人情况作出相应调整!