小程序获取后台数据方法封装

前言:

       实际再很早之前就有想再小程序里面做和vue中的axios封装的方法的操作,现在终于可以把自己的理解和整理封装整理下。

目录:

实现步骤:

1、目录结构,总共两个文件,http.js是对 wx.request 和 wx.uploadFile 的封装,可以实现普通请求后台和上传请求后台的调用

2、具体文件代码:

(1)http.js

源码:

(2)index.js 定义你的调用方法

源码:

3、封装后以后。我们在页面的调用


实现步骤:

1、目录结构,总共两个文件,http.js是对 wx.request 和 wx.uploadFile 的封装,可以实现普通请求后台和上传请求后台的调用

2、具体文件代码:

(1)http.js

*定义后台返回报错类型,根据后台的code来定义属于自己的校验信息

*正常请求后台的后台方法,跟我们vue相似

  •           url == 路径,
  •          methods == 请求方法 ,
  •          data == 参数(小程序只有这一个传参方法,没有我们vue的params)
  •          header == 请求头

*上传 后台 - 更多api请往最下面看

  •           url == 路径,
  •          methods == 请求方法 ,
  •          header == 请求头
  •          filePath == 要上传文件资源的路径 (本地路径)
  •          name == 文件对应的 key,开发者在服务端可以通过这个 key 获取文件的二进制内容
  •          formData == HTTP 请求中其他额外的 form data   ( 这里才是上传给后台加别的参数的地方 )

源码:

/*
* @Author: zwh
* @Date:  2020.6.23
*/
import { config } from '../config/index.js'

const tips = {
    1: '抱歉,出现了一个错误',
    205: '暂无数据!',
    300:'页面重定向,注意信息安全!',
    400:'语法格式有误!,请检查错误输入',
    401: '登录失败!',
    404:'页面资源错误!',
    500:'服务器错误!',

    10301:'用户不存在',
    11702:'手机经纬度获取失败',
    11703:'距离偏差太大',
    11704:'超时',


}

class HTTP {
    request({ url, data = {}, method = 'GET',type='' }) {
        return new Promise((resolve, reject) => {
            this._request(url, resolve, reject, data, method,type)
        })
    }
    _request(url, resolve, reject, data = {}, method = 'GET',type='') {
        try {
            var token = wx.getStorageSync('token')
            let header = {};
            if (token) {
                header = {
                    'X-Access-Mobile':token
                }
            }

            if(type == ''){
                //正常请求后台
                wx.request({
                    url: config.api_base_url + url,
                    method: method,
                    data: data,
                    header:header,
                    success: (res) => {
                        const code = res.statusCode.toString()
                        if (code.startsWith('2')) { // 一般情况下正确的请求结果是以2开头的(200)
                            resolve(res.data)

                        }else {
                            reject(res)
                            const error_code = res.data.code
                            this._show_error(error_code, res.data)

                        }
                    },
                    fail: (err) => {
                        reject(err)
                        this._show_error(1)
                    }
                })
            }else if(type == 'upload'){
                //上传请求后台
                wx.uploadFile({
                    url: config.api_base_url + url,
                    method: method,
                    header:header,
                    filePath:data.filePath,
                    name:data.name,
                    formData:data.formData,
                    success: (res) => {
                        const code = res.statusCode.toString()
                        if (code.startsWith('2')) { // 一般情况下正确的请求结果是以2开头的(200)
                            resolve(res.data)

                        }else {
                            reject(res)
                            let data =  JSON.parse(res.data);
                            const error_code = data.code;
                            this._show_error(error_code, data)

                        }
                    },
                    fail: (err) => {
                        reject(err)
                        this._show_error(1)
                    }
                })

            }



        } catch (e) {
            console.log(e);
        }


    }
    /**
     * 处理报错
     * */
    _show_error(error_code,data) {
        if (!error_code) {
            error_code = 1;//默认报错
        }
        const tip = tips[error_code] //= data.data
        wx.showToast({
            title: tip ? tip : tips[1],  // tips内没找到对应的错误代码时,使用1代替
            icon: 'none',
            duration: 2000
        })
    }

}

export { HTTP }

(2)index.js 定义你的调用方法

*正常请求:

*上传:

源码:


import { HTTP } from './http.js'

class DemoModel extends HTTP {
    // 登录-获取用户session_key
    getUserKey(data) {
        return this.request({ url: '/login', data: data, method: 'GET' })
    }
    // 获取当前用户签到信息
    getSignData(data) {
        return this.request({ url: '/employee', data: data, method: 'GET' })
    }
    // 获取手机号
    getPhone(data) {
        return this.request({ url: '/decry', data: data, method: 'PUT' })
    }



    /**
     * 上传
     * */
    //上传图片
    uploadImg(data){
        return this.request({
            url: '/sign',
            data: data,
            method: 'POST',
            type:'upload'
        })
    }


}

export {
    DemoModel
}

3、封装后以后。我们在页面的调用

index.js中使用:

import { DemoModel } from '../api/index.js'

const apiModel = new DemoModel();

正常操作:

              let str = {
                    code:res.code,
                }
                apiModel.getUserKey(str).then((res)=>{
                    let str = {
                        openid: res.openid,
                        session_key:res.session_key
                    }
                    this.setData({
                        userInfo:str
                    })
                    wx.setStorageSync('userInfo',str);
                    if(tit==1){
                        this.deciyption(res.session_key,encryptedDataStr,iv);
                    }
                }).catch(err=>{
                    console.log(err);
                })

上传操作:

                let str = {
                    filePath: tempFilePaths,
                    name: 'images',
                    formData: {
                        lon       :  that.data.map.longitude,
                        lat       :  that.data.map.latitude,
                        lat1       :  app.globalData.y_lat,
                        lon1       :   app.globalData.y_lon,
                        person_id :  that.data.user.person_id,
                        type      :  that.data.user.types=='3'?1:2,//3是上班,4是下班
                        location  :  that.data.map.title,
                    },
                }
                apiModel.uploadImg(str).then(res=>{
                    wx.hideLoading()
                    that.getSignData();//获取当前的签到信息
                    wx.showToast({
                        title: '打卡成功',
                        icon: 'success',
                        duration: 2000
                    })
                })

到此结束!

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浩星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值