用ES6的写了一个HTTP的class,在class里有两个方法
第一个是封装了request
第二个是(私有方法)接收请求的错误提示码,来给用户相应的反馈
const errs = { //错误提示码对应的意思 1: '默认的错误码', 1001: '那个啥未定义', 2001: '那个啥啥啥错误', 3001: '3XXXXXXXX'}class HTTP { request(params) { if (!params.method) { params.method = "GET" //如果没有穿method,那么method默认是GET } wx.repuest({ url: 'https://XXX.com.api' + params.url, data: params.data, method: params.method, header: { 'content-type': 'application/json' }, success: res => { let code = res.statusCode.toString(); if (code.startsWith('2')) { params.success(res.data) } else { let error_code = res.data.error_code this._show_error(error_code) } }, fail: (err) => { this._show_error(1) } }) } //错误提示, _show_error(error_code) { if (!error_code) { //如果没有错误提示码,默认的值1 error_code = 1 } wx.showToast({ title: errs[error_code], icon: 'none', duration: 2000 }) }}export { HTTP}//在需要的js文件里 import {HTTP} from '../http.js'//需要注意的是,需要使用一个类里的方法,不能直接HTTP.repuest,而是要用new来实例化一个类//let http=new HTTP()//http.request({// url:'XXX',// success:res=>{}//})复制代码