var API_BASE = 'https://api.lightmask.com' var USE_MOCK = true var mock = null if (USE_MOCK) { mock = require('./mock') } function request(options) { if (USE_MOCK && mock && mock.enabled) { return new Promise(function (resolve) { setTimeout(function () { var result = mock.handle(options.method || 'GET', options.path, options.data) if (result.code === 0) { resolve(result.data) } }, 200) }) } var token = wx.getStorageSync('token') return new Promise(function (resolve, reject) { wx.request({ url: API_BASE + options.path, method: options.method || 'GET', data: options.data || {}, header: Object.assign({ 'Authorization': token ? 'Bearer ' + token : '', 'Content-Type': 'application/json', 'X-App-Version': '1.0.0', 'X-Platform': 'wechat' }, options.header || {}), success: function (res) { if (res.data && res.data.code === 0) { resolve(res.data.data) } else if (res.data && res.data.code === 1001 || res.data && res.data.code === 1002) { wx.removeStorageSync('token') wx.reLaunch({ url: '/pages/login/login' }) reject(res.data) } else { reject(res.data || { code: -1, message: '请求失败' }) } }, fail: function (err) { reject({ code: 2002, message: err.errMsg || '网络异常' }) } }) }) } function get(path, data) { return request({ path: path, method: 'GET', data: data }) } function post(path, data) { return request({ path: path, method: 'POST', data: data }) } function put(path, data) { return request({ path: path, method: 'PUT', data: data }) } module.exports = { request: request, get: get, post: post, put: put, API_BASE: API_BASE }