62 lines
1.5 KiB
JavaScript
62 lines
1.5 KiB
JavaScript
const { API_BASE_URL } = require('./config')
|
|
|
|
function authHeader(extra = {}) {
|
|
const app = getApp()
|
|
return {
|
|
...(app.globalData.token ? { Authorization: `Bearer ${app.globalData.token}` } : {}),
|
|
...extra
|
|
}
|
|
}
|
|
|
|
function request(options) {
|
|
const app = getApp()
|
|
return new Promise((resolve, reject) => {
|
|
wx.request({
|
|
url: `${API_BASE_URL}${options.url}`,
|
|
method: options.method || 'GET',
|
|
data: options.data || {},
|
|
header: authHeader({ 'content-type': 'application/json', ...(options.header || {}) }),
|
|
success(res) {
|
|
if (res.statusCode >= 200 && res.statusCode < 300) {
|
|
resolve(res.data)
|
|
} else {
|
|
reject(new Error(res.data && res.data.detail ? res.data.detail : '请求失败'))
|
|
}
|
|
},
|
|
fail: reject
|
|
})
|
|
})
|
|
}
|
|
|
|
function uploadPalm(filePath) {
|
|
const app = getApp()
|
|
return new Promise((resolve, reject) => {
|
|
wx.uploadFile({
|
|
url: `${API_BASE_URL}/uploads/palm`,
|
|
filePath,
|
|
name: 'file',
|
|
header: authHeader(),
|
|
success(res) {
|
|
if (res.statusCode >= 200 && res.statusCode < 300) {
|
|
resolve(JSON.parse(res.data))
|
|
} else {
|
|
try {
|
|
const data = JSON.parse(res.data)
|
|
reject(new Error(data.detail || '上传失败'))
|
|
} catch (error) {
|
|
reject(new Error('上传失败'))
|
|
}
|
|
}
|
|
},
|
|
fail: reject
|
|
})
|
|
})
|
|
}
|
|
|
|
module.exports = {
|
|
API_BASE_URL,
|
|
authHeader,
|
|
request,
|
|
uploadPalm
|
|
}
|