集美们快看,小程序通用化的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 分钟前
前端和后端是怎么配合工作的(Go后端视角)
前端·golang·状态模式
w_t_y_y5 分钟前
vue父子组件通信(一)父子调用和通信(2)VUE3
前端·javascript·vue.js
Demon1_Coder8 分钟前
Day1-SpringAI-1.0.0版本
java·开发语言·前端
ZC跨境爬虫9 分钟前
跟着 MDN 学CSS day_42:等分轨道、层叠放置与混合布局
前端·javascript·css·ui·html
Cheney95019 分钟前
Vue 项目字体文件打包后 fonts 文件夹“消失”?原因分析与解决方案
前端·javascript·vue.js
问心无愧051316 分钟前
ctf show web入门68,69
android·前端·笔记
jingling55518 分钟前
Flutter | 从基本跳转到路由守卫
服务器·前端·网络·flutter·前端框架
神奇的代码在哪里24 分钟前
【单机离线版】大学考试题库复习工具:前端离线Excel解析 + localStorage持久化 + Playwright
前端·html·ai编程·题库复习·刷题软件·大学考试
daols8828 分钟前
vxe-table 实现数据分组统计与表尾合计
前端·javascript·vue.js·vxe-table
向日的葵00630 分钟前
Vue 函数定义、事件绑定与列表渲染精讲
前端·javascript·vue.js