微信小程序接口封装

247 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第2天,点击查看活动详情

为什么要封装?

当然是减少重复代码的编辑了!!少造几个螺丝多摸一会鱼儿不好嘛😊

流程

封装小程序原生接口wx.request

image.png

首先在utils文件夹里新建一个request.js文件,专门用来封装小程序的原生接口wx.request,根据接口的返回状态码来判断请求结果,并对不同状态码的结果进行处理。

比如,状态码statusCode为200时,代表请求成功,并返回了一些数据,你就可以弹出成功窗口,并跳转页面

    wx.request({
        url:url,
        method:'GET',
        complete:res=>{
            if(statusCode == 200){
                wx.showToast({
                    title:'请求成功!',
                    icon:'success',
                    duration:2000
                })
               setTimeout(() => { wx.reLaunch({ url: "/pages/home/home" }) }, 2000)
            }
        }
    })
const BASE_URL = 'https://localhost:8080'  //请求地址
const Loading = {   
    show() {
        wx.showLoading({
            title: '加载中..',
        })
    },
    hide() {
        wx.hideLoading()
    }
}

const myrequest = (url, method, data) => {
    let _url = BASE_URL + url
    Loading.show()
    return new Promise((resolve, reject) => {
        wx.request({
            url: _url,
            method: method,
            header: {
                'Authorization': token
            },
            data: data,
            success: res => {
                let status = res.statusCode;
                Loading.hide()
                if ((status >= 200 && status < 300) || status === 304) { // 成功的请求状态
                    resolve(res)
                } else {
                    let errMsg = res.data.message 
                    let route = ''
                    if (status == 401) route = 'login'
                    if (status == 403) route = 'home'
                    wx.showToast({
                        title: errMsg || '错误',
                        icon: 'none',
                        duration: 1500
                    })
                    if (route == 'login') {
                        wx.removeStorageSync()
                        setTimeout(() => {
                            wx.reLaunch({
                                url: "/pages/login/login"
                            })
                        }, 1500)
                    } else if (route == 'home') {
                        setTimeout(() => {
                            wx.switchTab({
                                url: "/pages/home/home"
                            })
                        }, 1500)
                    }
                }
            },
            fail: err => {
                Loading.hide()
                wx.showToast({
                    title: "请求WEB API 失败" + res.errMsg,
                    icon: 'none',
                    duration: 2000
                })
                reject(err)
            }
        })
    })

}

module.exports = {
    myrequest, BASE_URL
}
  1. 封装各模块请求接口地址

在utils文件夹里新建server文件夹

image.png

以用户信息模块举例

import { myrequest } from '../request.js'  

module.exports = {
    Login: data => {    //登录
        return myrequest('/api/Authenticate/login', 'POST', data)
    },
    UpdatePSW: data => {    //修改密码
        return myrequest('/api/Authenticate/UpdatePassword', 'GET', data)
    },
    LoginOut: data => {     //登出
        return myrequest('/api/Authenticate/LogOut', 'POST', data)
    }
}