vue3基于uni-app 封装小程序request请求

const BASE_URL = 'https://47.122.26.142'; // 替换为你的 API 基础 URL
const token = uni.getStorageSync('token');

const request = (url: string, method: any, data = {}, headers = {}) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${BASE_URL}${url}`,
      method,
      data,
      //请求头参数自定义
      header: {...headers, 'X-Token' : String(token)},
      timeout: 10000,
      success: (response) => {
        if (response.statusCode === 200) {
          resolve(response.data);
        } else {
          handleError(response);
          reject(response);
        }
      },
      fail: (error) => {
        uni.showToast({ title: '网络错误', icon: 'none' });
        reject(error);
      },
    });
  });
};

const handleError = (response: UniApp.RequestSuccessCallbackResult) => {
  switch (response.statusCode) {
    case 401:
      uni.showToast({ title: '请先登录', icon: 'none' });
      // 跳转到登录页的逻辑
      break;
    case 404:
      uni.showToast({ title: '资源未找到', icon: 'none' });
      break;
    default:
      uni.showToast({ title: '请求错误', icon: 'none' });
      break;
  }
};

const http = {
  get(url: string, params = {}, headers = {}) {
    console.log('请求参数', headers);
    return request(url, 'GET', params, headers);
  },
  post(url: any, data = {}, headers = {}) {
    return request(url, 'POST', data, headers);
  },
  put(url: any, data = {}, headers = {}) {
    return request(url, 'PUT', data, headers);
  },
  delete(url: any, data = {}, headers = {}) {
    return request(url, 'DELETE', data, headers);
  },
};

export default http;

使用新建interface.ts

import http from '@/utils/request'
const application = "application/json;charset=UTF-8";
const formData = "multipart/form-data";
const plain = "application/json, text/plain, */*";

const {post, get, put} = http

// Content-Type 根据实际接口选择
export const apiGetMyNotice = (data: any) => {
  return get(`/api/workflowProcess/getMyNotice`, data, {"Content-Type":application});
};

在页面使用同常规一样

<script setup lang="ts">
import { apiGetMyNotice } from "@/apis/interface";
import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
import { computed, onMounted, reactive } from "vue";


onMounted(() => {
  onApiGetMyNotice();
});
const onApiGetMyNotice = async () => {
  try {
    const response = await apiGetMyNotice({});
    console.log(response);
  } catch (error) {
    console.error(error);
  }
};
</script>

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jim-zf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值