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

四、效果演示

相关推荐
计算机毕设指导65 分钟前
基于微信小程序的智能停车场管理系统【源码文末联系】
java·spring boot·微信小程序·小程序·tomcat·maven·intellij-idea
晚霞的不甘9 分钟前
Flutter for OpenHarmony手势涂鸦画板开发详解
前端·学习·flutter·前端框架·交互
We་ct14 分钟前
LeetCode 73. 矩阵置零:原地算法实现与优化解析
前端·算法·leetcode·矩阵·typescript
晚霞的不甘15 分钟前
Flutter for OpenHarmony 实现动态天气与空气质量仪表盘:从 UI 到动画的完整解析
前端·flutter·ui·前端框架·交互
~小仙女~18 分钟前
组件的二次封装
前端·javascript·vue.js
这是个栗子22 分钟前
AI辅助编程(一) - ChatGPT
前端·vue.js·人工智能·chatgpt
2501_9444480023 分钟前
Flutter for OpenHarmony衣橱管家App实战:预算管理实现
前端·javascript·flutter
Remember_99326 分钟前
Spring 核心原理深度解析:Bean 作用域、生命周期与 Spring Boot 自动配置
java·前端·spring boot·后端·spring·面试
笨蛋不要掉眼泪29 分钟前
Redis持久化解析:RDB和AOF的对比
前端·javascript·redis
心.c32 分钟前
Vue3+Node.js实现文件上传分片上传和断点续传【详细教程】
前端·javascript·vue.js·算法·node.js·哈希算法