Files
inchstep/miniapp/services/api.js
T
2026-06-25 08:39:47 +08:00

37 lines
1.1 KiB
JavaScript

const app = getApp()
function request(path, options = {}) {
return new Promise((resolve, reject) => {
const header = { 'Content-Type': 'application/json' }
if (app.globalData.token) header['Authorization'] = 'Bearer ' + app.globalData.token
wx.request({
url: app.globalData.apiUrl + path,
method: options.method || 'GET',
data: options.data,
header,
success(res) {
const body = res.data
if (body.code === 0) {
resolve(body.data)
} else {
if (body.code === 401) {
wx.removeStorageSync('token')
wx.removeStorageSync('user')
wx.reLaunch({ url: '/pages/login/index' })
}
reject(new Error(body.message))
}
},
fail(err) { reject(new Error('网络请求失败')) }
})
})
}
module.exports = {
get: (path) => request(path),
post: (path, data) => request(path, { method: 'POST', data }),
put: (path, data) => request(path, { method: 'PUT', data }),
del: (path) => request(path, { method: 'DELETE' }),
}