65 lines
1.9 KiB
JavaScript

/**
* HTTP 请求封装 - 对应 JS 版 bricks.HttpJson/HttpText
*/
const app = getApp()
class BricksHttp {
/**
* GET 请求
*/
get(url, params = {}) {
return new Promise((resolve, reject) => {
const fullUrl = this._withBricksContext(app.entireUrl(url))
wx.request({
url: fullUrl,
data: params,
method: 'GET',
header: {
'Content-Type': 'application/json',
'Authorization': app.globalData.authToken ? `Bearer ${app.globalData.authToken}` : ''
},
success: (res) => {
if (res.statusCode === 200) resolve(res.data)
else reject(new Error(`HTTP ${res.statusCode}`))
},
fail: (err) => reject(err)
})
})
}
/**
* POST 请求
*/
post(url, data = {}) {
return new Promise((resolve, reject) => {
const fullUrl = this._withBricksContext(app.entireUrl(url))
wx.request({
url: fullUrl,
data: JSON.stringify(data),
method: 'POST',
header: {
'Content-Type': 'application/json',
'Authorization': app.globalData.authToken ? `Bearer ${app.globalData.authToken}` : ''
},
success: (res) => {
if (res.statusCode === 200) resolve(res.data)
else reject(new Error(`HTTP ${res.statusCode}`))
},
fail: (err) => reject(err)
})
})
}
_withBricksContext(url) {
if (!/\.(ui|dspy)(\?|$)/.test(url)) return url
const info = wx.getSystemInfoSync ? wx.getSystemInfoSync() : {}
const clean = url.replace(/([?&])(_webbricks_|_width|_height|_is_mobile|_lang)=[^&]*&?/g, '$1').replace(/[?&]$/, '')
const join = clean.indexOf('?') >= 0 ? '&' : '?'
return clean + join + '_webbricks_=1&_width=' + encodeURIComponent(info.windowWidth || 0) +
'&_height=' + encodeURIComponent(info.windowHeight || 0) +
'&_is_mobile=1&_lang=' + encodeURIComponent(info.language || 'zh-CN')
}
}
module.exports = { BricksHttp }