const config = require('../config') function networkError(err) { const msg = (err && err.errMsg) || '' if (msg.indexOf('url not in domain list') >= 0 || msg.indexOf('合法域名') >= 0) { return new Error('请勾选:不校验合法域名') } return new Error('网络异常,请确认后端已启动') } function apiError(statusCode, body) { const error = new Error((body && body.message) || '请求失败') error.statusCode = statusCode return error } function authHeader(header) { const token = wx.getStorageSync('token') if (token) header.Authorization = token return header } function handle(statusCode, body, auth, resolve, reject) { if (statusCode === 401 && auth) wx.removeStorageSync('token') if (statusCode >= 200 && statusCode < 300 && body && body.ok !== false) { resolve(body.data) return } reject(apiError(statusCode, body)) } function request(options) { const auth = !!options.auth const header = { 'content-type': 'application/json' } return new Promise((resolve, reject) => { wx.request({ url: config.BASE + options.url, method: options.method || 'GET', data: options.data, header: auth ? authHeader(header) : header, success(res) { handle(res.statusCode, res.data || {}, auth, resolve, reject) }, fail(err) { reject(networkError(err)) } }) }) } function upload(options) { return new Promise((resolve, reject) => { wx.uploadFile({ url: config.BASE + options.url, filePath: options.filePath, name: 'file', header: authHeader({}), success(res) { let body = null try { body = JSON.parse(res.data || '{}') } catch (error) { reject(new Error('上传返回异常')) return } handle(res.statusCode, body, true, resolve, reject) }, fail(err) { reject(networkError(err)) } }) }) } module.exports = { request: request, upload: upload }