刚出炉热乎的。UniApp X 封装 uni.request

HBuilder X v4.66 当前最新版本

由于 uniapp x 使用的是自己包装的 ts 语言 uts。目前语言还没有稳定下来,各种不支持 ts 各种报错各种不兼容问题。我一个个问题调通的,代码如下:

封装方法

TypeScript 复制代码
// my-app/utils/request.uts
const UNI_APP_BASE_URL = "http://192.168.1.1:8080"	// 开发环境
// const UNI_APP_BASE_URL = "http://test.com"	// 测试环境
// const UNI_APP_BASE_URL = "http://pro.com"	// 正式环境

type JsonResult = {
	code : number;	// 状态码
	data ?: any;	// 返回数据
	msg ?: string;	// 返回消息
}

export function get(uri : string, data : any = {}) : Promise<JsonResult> {
	const url = UNI_APP_BASE_URL + uri;
	return new Promise((resolve, reject) => {
		uni.request<JsonResult>({
			url,
			method: "GET",
			data,
			success: (response) => {
				const jsonResult = response.data
				if (jsonResult != null) {
					if (jsonResult.code != 0) {
						uni.showToast({ title: jsonResult.msg ?? "出错了", icon: 'none' })
					}
					resolve(jsonResult);
				}
			}, fail: (err) => {
				console.error("错误信息:", err)
				uni.showToast({ title: "app 错误 " + err.errMsg, icon: 'none' })
				reject(err);
			}
		})
	})
}

export function post(uri : string, data : any = {}) : Promise<JsonResult> {
	const url = UNI_APP_BASE_URL + uri;
	return new Promise((resolve, reject) => {
		uni.request<JsonResult>({
			url,
			method: "POST",
			data,
			success: (response) => {
				const jsonResult = response.data
				if (jsonResult != null) {
					if (jsonResult.code != 0) {
						uni.showToast({ title: jsonResult.msg ?? "出错了", icon: 'none' })
					}
					resolve(jsonResult);
				}
			}, fail: (err) => {
				console.error("错误信息:", err)
				uni.showToast({ title: "app 错误 " + err.errMsg, icon: 'none' })
				reject(err);
			}
		})
	})
}

如下使用:

TypeScript 复制代码
<script setup lang="uts">
	import { post } from '@/utils/request.uts';
	async function login() {
		try {
			const jsonResult = await post("/login", { mobile: "11111111111", code: "111111", grantType: "sms" });
			console.log("请求返回数据:", jsonResult);
		} catch (err) {
			console.error("请求失败:", err);
		}
	}
	login();
</script>
相关推荐
暗不需求1 分钟前
深入理解 LangChain:AI 应用开发框架的工程化实践
前端·langchain
用户0595401744622 分钟前
把 Redis 持久化测试从 800 行 Shell 换成 30 行 pytest,排错效率翻了 10 倍
前端·css
GISer_Jing27 分钟前
AI全栈工程师知识体系全景:从前后端核心架构到落地项目全拆解
前端·人工智能·后端·ai编程
Wect32 分钟前
深度剖析浏览器跨域问题
前端·面试·浏览器
陈随易1 小时前
bun将会支持Bun.image,你怎么看?
前端·后端·程序员
jingqingdai31 小时前
别用正则格式化 HTML!我用 DOM 遍历实现零风险本地格式化,老项目重构效率直接拉满
前端·重构·html
木斯佳1 小时前
前端八股文面经大全:腾讯前端实习二、三OC面(2026-04-27)·面经深度解析
前端·状态模式
Python私教1 小时前
如意Agent日志系统重构:从 print() 大海捞针到结构化可观测性栈
java·前端·重构
We་ct2 小时前
LeetCode 97. 交错字符串:动态规划详解
前端·算法·leetcode·typescript·动态规划