12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- import {wxToPromise} from "./wx";
- import config from "../model/config";
- import Route from "../model/route";
- import User from "../model/user";
- import {showLoading} from "./utils";
- const app = getApp();
- class Http {
- static async request({url, data, method = 'get', opt = {isLoading: false}}) {
- const isLoading = opt.isLoading;
- if (isLoading) {
- showLoading();
- }
- let res
- try {
- let tokenObj = {};
- if (app.globalData.token) {
- tokenObj.Authorization = app.globalData.token;
- }
- res = await wxToPromise('request', {
- url: `${config.API}${url}`,
- data,
- method,
- header: {
- 'content-type': 'application/json',
- ...tokenObj
- }
- })
- } catch (e) {
- console.log('网络错误', e);
- // 代码逻辑异常、无网络、请求超时会走这里
- Http._showError(-100)
- throw new Error(e.errMsg)
- }
- if (isLoading) {
- wx.hideLoading()
- }
- if (res.statusCode == 200) {
- if (res.data.code == 200) {
- console.log(`网络请求${url}`, data, res.data);
- return res.data;
- } else if (res.data.code == 401) {
- Route.toLogin();
- User.logout();
- } else if (res.data.code == 511) {//针对提交 重复的,直接判断为成功,但是结果不会存在了
- console.log(`网络请求${url}重复提交`, data, res.data);
- return res.data;
- } else {
- Http._showError(res.data.code, res.data.msg)
- throw new Error(res.data.msg)
- }
- } else {
- Http._showError(res.statusCode)
- throw new Error(res.statusCode)
- }
- }
- static _showError(errorCode, message = '') {
- const errorMessage = config.ERROR_MSG[errorCode];
- const title = errorMessage || message || '未知异常'
- console.log("错误提示", title)
- wx.showToast({
- title,
- icon: 'none',
- duration: 3000
- })
- }
- }
- export default Http
|