集美们快看,小程序通用化的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会重新赋值

四、效果演示

相关推荐
摸鱼的春哥3 分钟前
Agent教程15:认识LangChain(中),状态机思维
前端·javascript·后端
明月_清风9 分钟前
告别遮挡:用 scroll-padding 实现优雅的锚点跳转
前端·javascript
明月_清风12 分钟前
原生 JS 侧边栏缩放:从 DOM 监听到底层优化
前端·javascript
万少9 小时前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站11 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名14 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫14 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊14 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter14 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折14 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium