更新记录

1.0.7(2024-06-27)

优化

1.0.6(2024-06-21)

优化写法

1.0.5(2024-06-07)

优化文档

查看更多

平台兼容性

Vue2 Vue3
App 快应用 微信小程序 支付宝小程序 百度小程序 字节小程序 QQ小程序
HBuilderX 4.15,Android:支持,iOS:支持 × × × × × ×
钉钉小程序 快手小程序 飞书小程序 京东小程序
× × × ×
H5-Safari Android Browser 微信浏览器(Android) QQ浏览器(Android) Chrome IE Edge Firefox PC-Safari
× × × × × × × ×

yq-request-uts 封装request promise写法 async+await 支持 GET,POST,PUT,DELETE,HEAD,OPTIONS,PATCH

自定义请求头,更加灵活,自定义层业务层错误处理函数,支持外部接口

使用方法 App.vue代码如下

<script lang="uts">
    let firstBackTime = 0
    export default {
        onLaunch: function () {
            console.log('App Launch')
            this.setBaseUrl()
        },
        onShow: function () {
            console.log('App Show')
        },
        onHide: function () {
            console.log('App Hide')
        },
        // #ifdef APP-ANDROID
        onLastPageBackPress: function () {
            console.log('App LastPageBackPress')
            if (firstBackTime == 0) {
                uni.showToast({
                    title: '再按一次退出应用',
                    position: 'bottom',
                })
                firstBackTime = Date.now()
                setTimeout(() => {
                    firstBackTime = 0
                }, 2000)
            } else if (Date.now() - firstBackTime < 2000) {
                firstBackTime = Date.now()
                uni.exit()
            }
        },
        // #endif
        onExit: function () {
            console.log('App Exit')
        },
        globalData: {
            baseUrl:'',
            devUrl: 'http://dev.com',
            proUrl: 'http://pro.com',
            baiduUrl: 'http:baidu.com',
            /**
             * http请求成功的状态码
             */
            httpSuccessCodes: [200, 201, 202, 203, 204, 205, 206], 

            /**
             * 处理服务器httpcode是401
             */
            http401() {
                // 如果有返回http的statuscode是401,可以在这里处理逻辑
            },
            /**
             * 业务层错误处理函数
             */
            systemError(res:UTSJSONObject):boolean{
                if (res['code'] == 401) { //这里必须是== 
                    uni.showToast({
                        title: '登录过期',
                        icon: 'error'
                    });
                    return true;
                } else if (res['code'] == 500) { 
                    uni.showToast({
                        title: res['message'] as string,
                        icon: 'none',
                        duration: 2500
                    });
                    return true;
                }else{
                    // return false的时候就是就是正常接收数据,return true就会拦截
                    return false;
                }

            },
            /**
             * 设置请求头
             */
            setHeader(auth:boolean,formData:boolean):UTSJSONObject {
                let header = {
                    'content-type': 'application/json',
                    clientType: 'C',
                    communityId: uni.getStorageSync('communityId'),
                    Authorization:uni.getStorageSync('token')
                };
                // 一些项目的post的请求头需要设置为x-www-form-urlencoded,可以在接口里设置为formData = true
                if (formData) {
                    header['content-type'] = 'application/x-www-form-urlencoded'
                }
                // auth代表是否鉴权,默认是,如果不需要传Authorization等,可以在接口里设置为auth = false
                if (!auth) {
                    header['Authorization'] = null 
                }
                return header
            }
        },
        methods: {
            /**
             * 请求配置
             */
            setBaseUrl():void {
                if (process.env.NODE_ENV == 'development') {
                    // 开发环境 运行
                    // #ifdef H5
                    this.globalData.baseUrl = location.origin;
                    // #endif
                    // #ifndef H5
                    // @ts-ignore
                    this.globalData.baseUrl = this.globalData.devUrl;
                    // #endif
                } else {
                    // 生产环境 发行
                    // @ts-ignore
                    this.globalData.baseUrl = this.globalData.proUrl;
                }
            }
        }
    }
</script>

如果有h5需要配置跨域代理,项目在根目录创建vite.config.js

import { defineConfig } from 'vite';
import uni from '@dcloudio/vite-plugin-uni';
export default defineConfig({
    plugins: [
        uni(),
    ],
    server: {
      proxy: {
        '/api/': {
          target: 'http://192.168.1.110:8000.com',
          changeOrigin: true,
        }
      },
    },
});

和pages文件夹同级创建apis文件夹,用来放置接口文件 (文件夹名不要用api,因为h5配置代理会把所有api后的路径代理,所以要改成apis)

以apis文件的index.uts为例,代码如下

import { request, IParams } from '@/uni_modules/yq-request-uts/utssdk/index';

/**
 * 首页商品列表接口 post的formData形式
 */
export const goodsApi = (data : UTSJSONObject) : Promise<any> => {
    const requestData : IParams = {
        method: 'POST',
        api: '/api/goodsPage',
        data,
        formData:true,
    };
    return request(requestData);
};

/**
 * 首页商品列表接口 post的json形式
 */

export const goodsJsonApi = (data : UTSJSONObject) : Promise<any> => {
    const requestData : IParams = {
        method: 'POST',
        api: '/api/goodsPageJson',
        data,
    };
    return request(requestData);
};

/**
 * 首页公示公告列表接口 get
 */

export const newsApi = (data : UTSJSONObject) : Promise<any> => {
    const requestData : IParams = {
        api: '/api/newsPage',
        data,
    };
    return request(requestData);
};

/**
 * 外部接口 get 不需要鉴权auth设置为false
 */
export const baiduApi = (data : UTSJSONObject) : Promise<any> => {
    const requestData : IParams = {
        url:getApp().globalData.baiduUrl, // 示例url
        api: '/api/listIndex',
        auth:false,
        data,
    };
    return request(requestData);
};

在uvue中使用

<template>
    <view class="content">
        <image class="logo" src="/static/logo.png"></image>
    </view>
</template>

<script setup lang="uts">
import { goodsApi, newsApi } from '@/apis/index';
import { onShow } from '@dcloudio/uni-app';

/**
 * 获取商品
 */
const getGoods = async () => {
    const res = await goodsApi();
    console.log('res', res);
};

/**
 * 获取公示公告
 */
const getNews = async () => {
    const res = await newsApi();
    console.log('res', res);
};

onShow(() => {
    getGoods();
    getNews();
});
</script>

隐私、权限声明

1. 本插件需要申请的系统权限列表:

2. 本插件采集的数据、发送的服务器地址、以及数据用途说明:

3. 本插件是否包含广告,如包含需详细说明广告表达方式、展示频率:

许可协议

MIT协议

使用中有什么不明白的地方,就向插件作者提问吧~ 我要提问