wx.request 微信小程序请求上传封装
目录utils下新建文件wx-prototype.js:
const host = 'https://***'
const alert = title =>{
wx.showToast({
title: title,
icon: 'none'
})
}
const getRequestOptions = options => {
const url = host + options.url
const header = {
api_token: wx.getStorageSync('api_token'),
"Content-Type": "application/json"
}
options.url = host + options.url
//loading 传false表示不展现请求弹窗,传文字展示所传文字,不传展示默认
options.loading === false ? null : typeof options.loading === 'string' ? wx.showLoading({
title: loading,
}): wx.showLoading({
title: '请稍后...',
})
return Object.assign(options, { url, header });
}
const get = options => {
options.method = 'get'
return new Promise((resolve, reject)=>{
request(getRequestOptions(options), resolve, reject)
})
}
const post = options => {
options.method = 'post'
return new Promise((resolve, reject)=>{
request(getRequestOptions(options), resolve, reject)
})
}
const request = (options, resolve, reject) => {
options.data = options.data || {}
//后端同学非要把token放请求参数里面,没得办法
options.data.api_token = wx.getStorageSync('api_token'),
wx.request({
...options,
success: (res) => {
wx.hideLoading()
wx.stopPullDownRefresh()
const data = res.data
if (data.status == 1) {
wx.setStorageSync('isLoginPage', false)
resolve(data)
} else if (data.status == 400) {
wx.setStorageSync('isLoginPage', false)
alert('数据不存在')
} else if (data.status == 401) {
alert('没有权限')
const isLoginPage = wx.getStorageSync('isLoginPage')
if (isLoginPage) return;
setTimeout(_ => {
//防止一个页面有两个请求时,跳转两次登录页
wx.setStorageSync('isLoginPage', true)
wx.redirectTo({
url: '/pages/login/login',
})
wx.setStorageSync('isLoginPage', false)
}, 2000)
} else {
alert(data.message || '请求错误')
}
},
fail: (error) => {
wx.hideLoading()
wx.stopPullDownRefresh()
alert(JSON.stringify(error))
reject(error)
}
})
}
// 这里比较懒,直接挂到wx上了
wx.$get = get
wx.$post = post
wx.$upload = upload
wx.$alert = alert
app.js里面:
使用方法:
Page({
data: {
data: {
list: [],
page: 1,
total: 0
},
onLoad: function (options) {
this.getData()
},
getData() {
wx.$get({
url: '/list',
data: {
group: 'system',
page: this.data.page
}
}).then(res => {
const data = res.data
const list = this.data.list
list.push(...data.data)
this.setData({
list: list
})
})
},
onReachBottom() {
this.data.page += 1
this.getData()
}
},
下一篇,微信小程序上传至腾讯云:https://www.jianshu.com/p/168aed3265ab