集美们快看,小程序通用化的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 小时前
12 web 自动化之基于关键字+数据驱动-反射自动化框架搭建
运维·前端·自动化
小嘟嚷ovo3 小时前
h5,原生html,echarts关系网实现
前端·html·echarts
十一吖i4 小时前
Vue3项目使用ElDrawer后select方法不生效
前端
只可远观4 小时前
Flutter目录结构介绍、入口、Widget、Center组件、Text组件、MaterialApp组件、Scaffold组件
前端·flutter
周胡杰4 小时前
组件导航 (HMRouter)+flutter项目搭建-混合开发+分栏效果
前端·flutter·华为·harmonyos·鸿蒙·鸿蒙系统
敲代码的小吉米4 小时前
前端上传el-upload、原生input本地文件pdf格式(纯前端预览本地文件不走后端接口)
前端·javascript·pdf·状态模式
是千千千熠啊4 小时前
vue使用Fabric和pdfjs完成合同签章及批注
前端·vue.js
九月TTS5 小时前
TTS-Web-Vue系列:组件逻辑分离与模块化重构
前端·vue.js·重构
我是大头鸟5 小时前
SpringMVC 内容协商处理
前端
Humbunklung5 小时前
Visual Studio 2022 中添加“高级保存选项”及解决编码问题
前端·c++·webview·visual studio