wx.request 微信小程序請(qǐng)求上傳封裝
目錄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表示不展現(xiàn)請(qǐng)求彈窗焰情,傳文字展示所傳文字掌实,不傳展示默認(rèn)
options.loading === false ? null : typeof options.loading === 'string' ? wx.showLoading({
title: loading,
}): wx.showLoading({
title: '請(qǐng)稍后...',
})
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 || {}
//后端同學(xué)非要把token放請(qǐng)求參數(shù)里面,沒得辦法??
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('數(shù)據(jù)不存在')
} else if (data.status == 401) {
alert('沒有權(quán)限')
const isLoginPage = wx.getStorageSync('isLoginPage')
if (isLoginPage) return;
setTimeout(_ => {
//防止一個(gè)頁(yè)面有兩個(gè)請(qǐng)求時(shí),跳轉(zhuǎn)兩次登錄頁(yè)
wx.setStorageSync('isLoginPage', true)
wx.redirectTo({
url: '/pages/login/login',
})
wx.setStorageSync('isLoginPage', false)
}, 2000)
} else {
alert(data.message || '請(qǐng)求錯(cuò)誤')
}
},
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()
}
},
下一篇铸磅,微信小程序上傳至騰訊云:http://www.reibang.com/p/168aed3265ab