Uni-app 封装uni.request请求 vue3 ts版本

1、request.ts


import environment from '../environments' // 环境,服务配置文件
import { userStore } from '@/store/modules/user'
console.log(process.env.NODE_ENV)


const baseUrl = environment.envConfigs.url
const apiServe = environment.SERVE_CTX
const VITE_APP_MODE = import.meta.env.VITE_APP_MODE

const CONTENT_TYPE = {
    JSON: 'application/json;charset=UTF-8',
    FORM_URLENCODED: 'application/x-www-form-urlencoded;charset=UTF-8',
    FORM_DATA: 'multipart/form-data;charset=UTF-8',
}

export interface requestType {
    code: number
    data?: any
    message: string
    status: boolean
}
type ServeType = 'AUTH' | 'PROPERTY' | 'FILE' | 'JOB' | 'BPM'

type HttpMethod = 'POST' | 'OPTIONS' | 'GET' | 'HEAD' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT'
type ContentType = 'JSON' | 'FORM_URLENCODED'
const DEFAULT_SERVE: ServeType = 'AUTH'
const DEFAULT_METHOD: HttpMethod = 'GET'
const DEFAULT_CONTENT_TYPE: ContentType = 'JSON'

interface Request {
    serve?: ServeType
    url: string
    method: HttpMethod
    body?: any
    hideLoading?: boolean
    contentType?: ContentType
    headers?: any
    timeout?: number
}
const request = async ({
    serve = DEFAULT_SERVE,
    url = '',
    method = DEFAULT_METHOD,
    body = {},
    hideLoading = true, //是否显示请求loading
    contentType = DEFAULT_CONTENT_TYPE,
    headers = {},
    timeout = 6000,
}: Request): Promise<requestType> => {
    if (!hideLoading) {
        uni.showLoading({
            mask: true,
        })
    }
    url = baseUrl + apiServe[serve] + url
    const requestUrl = url
    const token = await userStore().token
    const authHeaders = {
        Authorization: token ? `Bearer ${token}` : '',
        Cookie: token ? `access_token=Bearer ${token}` : '',
    }
    try {
        const res: any = await uni.request({
            url: requestUrl,
            method: method,
            data: body,
            header: Object.assign(authHeaders, headers),
            timeout,
            enableCache: true, // 自动处理缓存
        })

        const { data }: any = res

        if (res.data.code === 606) {
            //需要重新登录清除store
            userStore().$reset()
            uni.reLaunch({
                url:'',
            })
            return Promise.reject('需要重新登录')
        }

        if (res.statusCode !== 200) {
            uni.showToast({
                icon: 'none',
                title: '系统错误!',
            })
            return Promise.reject('系统错误')
        }

        if (res.data.code === 200) {
            return Promise.resolve(data)
        }
        uni.showToast({
            icon: 'none',
            title: res.data.message,
        })
        //异常抛出
        return Promise.reject(res.data.message)
    } catch (error) {
        return Promise.reject('请求失败')
    } finally {
        if (!hideLoading) {
            uni.hideLoading({
                noConflict: true, //解决微信小程序Loading 和 showToast无法共用
            })
        }
    }
}
export default request

 2、login-serice.ts


import request from '@/utils/request'

export const getPhoneNumber = (data: any) => {
    return request({
        url: '',
        method: 'POST',
        body: data,
        hideLoading: false,
    })
}

 3、页面使用login.vue 

<template>

</template>
<script setup lang="ts">
  import { login } from '@/api/login'
  const submit = async () => {
    try{
        const res = await login()
      } catch {
    }
  }
</script>

4、environments.ts文件

const env: string | undefined = process.env.NODE_ENV
const SERVE_CTX = {
    AUTH: '',
}
const configs: any = {
    // 生产环境
    production: {
        url: ''
        
    },
    // 开发环境
    development: {
        // #ifdef  H5
        url: '/api',
        // #endif

        //@ts-ignore
        // #ifdef  APP-PLUS | MP-WEIXIN
        url: ''
        // #endif
    },
}

const envConfigs: {
    url: string
} = configs[env as string]

export default { envConfigs, SERVE_CTX }
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值