集美们快看,小程序通用化的https请求封装

一、封装前的准备

先在项目上起一个名为service的目录,里面放request和api两个js文件

二、封装第一步:request.js

js 复制代码
const baseUrl = 'xxxx'
export const appid = 'xxx'
export const applet_id = 'xxx'

/**
 * @description: 小程序https请求封装
 * @return {*}
 */

class HttpRequest {
    constructor(requestConfig, backendConfig) {
        this.requestConfig = requestConfig
        this.backendConfig = backendConfig
    }

    /**
     * @description: 
     * @param {*} params
     * @return {*}
     */
    async request(options) {
        const {
            url,
            data = {},
            method = this.requestConfig.method,
            dataType = this.requestConfig.dataType,
        } = options
        await checkSession()
        const userInfo = my.getStorageSync({ key: 'userInfo' }).data
        if (data.hasOwnProperty('user_id') && data.user_id === '') {
            data.user_id = userInfo.user_id
        }
        return new Promise(async (resolve, reject) => {
            my.request({
                url: `${baseUrl}${url}`,
                data,
                method,
                headers: {},
                dataType,
                success: (res) => {
                    // 后端接口返回的值,false为报错
                    if (!res.data.status) {
                        // 错误信息
                        resolve(res.data)
                    } else {
                        // 成功后的数据对象
                        resolve(res.data.data)
                    }
                }
            })
        })
    }
}

/**
* @description: 校验登陆态
*/
async function checkSession() {
    const userInfo = my.getStorageSync({ key: 'userInfo' }).data
    if (!userInfo) {
        const res = await getCode()
        my.setStorageSync({
            key: 'userInfo',
            data: res
        })
    } else {
        if (appid !== userInfo.appid) {
            const res = await getCode()
            my.setStorageSync({
                key: 'userInfo',
                data: res
            })
        }
    }
}

async function getCode() {
    const { authCode } = await my.getAuthCode()
    return new Promise((resolve) => {
        my.request({
            url: `${baseUrl}/getinfo`,
            method: 'POST',
            data: {
                applet_id,
                auth_code: authCode
            },
            success(res) {
                resolve(res.data.data)
            }
        })
    })
}

const defaultRequestConfig = {
    headers: {
        'content-type': 'application/json'
    },
    dataType: 'json',
    method: 'POST'
}

export const myRequest = new HttpRequest(defaultRequestConfig, {
    baseUrl,
    codeKey: 'code',
    dataKey: 'data',
    successCode: 200,
})

2.1 接口在请求之前判断是否登录,如果未登录则先调用登录操作,把user_id记录在缓存里面,下次接口请求就不需要进行登录了,这里我用的是支付宝的开放接口,根据小伙伴的不同需要,可以改成微信小程序和uniapp。(wx.request和uni.request)

三、封装第二步:api.js

js 复制代码
import { myRequest, applet_id, appid } from "./request";

const userInfo = my.getStorageSync({ key: 'userInfo' }).data || { appid: '', user_id: '' }

/** 
 * 首页数据获取
*/
export async function fetchBankcard() {
    return myRequest.request({
        url: '/bankcard',
        data: {
            applet_id,
            user_id: userInfo.user_id
        }
    })
}

3.1 这里获取登录信息,如果没有则为空,然后会走request文件的逻辑,进行登陆,然后user_id会重新赋值

四、效果演示

相关推荐
Moment26 分钟前
写给迷茫的应届生,怎样在 AI 时代争取更多机会
前端·后端·面试
fengci.33 分钟前
CTF2MISC中等部分
开发语言·前端·学习
涛涛ing41 分钟前
那个PR太干净了,干净到我差点直接点了合并
前端
去伪存真43 分钟前
稠密检索负责脑补,稀疏检索负责兜底:拆解 RAG 倒排索引的“查字典”艺术
前端·agent
喵个咪2 小时前
GoWind 拆解:全链 ID 类型体系——int64 定版与前端字符串化契约
前端·后端·go
喵个咪2 小时前
GoWind CMS 拆解:Flutter 设计系统内核——双态 token、四档断点与自适应壳层
前端·flutter·交互设计
喵个咪2 小时前
GoWind CMS 拆解:发布审批——多级推进、逐级角色与全程留痕
前端·后端·go
喵个咪2 小时前
GoWind Flow 拆解:一个 Go 工作流引擎与它的双模式设计器
前端·后端·go
喵个咪3 小时前
GoWind Admin 拆解:打印模板设计器——从画布到服务端 PDF 的完整打印链路
前端·后端·go
总要学点什么3 小时前
第96篇:三维数据加载-城市建筑白模样式+着色器——让色带按体量上色,最白的那档却涂不上去
前端·gis·webgl·cesium·着色器·空间分析·白模