wx.request封装

2,073 阅读1分钟

wx.request封装

  1. 定义config配置选项
//新建config.js
const config = {
    baseUrl: 'http://www.baidu.com/api', //示例
    appKey: 'xxxx',
}

export default config;

export 与export default

  • export可以导出多个模块
  • export default只能导出单一模块
  1. 新建http类封装请求
//新建util/http.js
// 导入config配置项
import config from '../config';

//定义错误码
const err_tip = {
    1: '出现了一个错误',
    10001: 'xxxx',
    10002: 'xxxx'
}
class HttpRequest{
    request(params){
        wx.request({
            url: config.url + params.url,
            method: params.method || 'GET',
            data: params.data,
            header: {
                'content-type': 'application/json',
                appKey: config.appKey, //
            },
            success: (res) => {
                let code = res.statusCode;
                if(code.startsWith('2')){
                    // 调用成功函数
                    params.success(res.data)
                } else {
                    // 错误处理 
                    // 一般提前定义好错误码,为用户提示友好的错误信息
                    this._show_errMsg(res.data.error_code)
                    console.log('err',res.data)
                }
            },
            fail: (err) => {
                this._show_errMsg(1)
            }
        })
    }
    
    _show_errMsg(err_code){
        if(!err_code){
            wx.showToast({
                title: err_tip[1],
                icon: 'none',
                duration: 1500
            })
        }
        wx.showToast({
            title: err_tip[err_code],
            icon: 'none',
            duration: 1500
        })
    }
}
export default HttpRequest;
  1. 在页面中使用
import HttpRequest from '../../util/http.js';

let http = new HttpRequest()
onLoad: function(){
    http.request({
        url: '/xxx/xx',
        method: 'POST',
        // 'GET'请求可不写
        data: {xxx,yyy},
        success: (res) => {
            console.log(res.data)
        }
    })
}

感谢7yue老师的课程