刚出炉热乎的。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>
相关推荐
He少年1 天前
【基础知识、Skill、Rules和MCP案例介绍】
java·前端·python
史迪仔01121 天前
[QML] QML IMage图像处理
开发语言·前端·javascript·c++·qt
AwesomeCPA1 天前
Miaoduo MCP 使用指南(VDI内网环境)
前端·ui·ai编程
前端大波1 天前
前端面试通关包(2026版,完整版)
前端·面试·职场和发展
qq_433502181 天前
Codex cli 飞书文档创建进阶实用命令 + Skill 创建&使用 小白完整教程
java·前端·飞书
IT_陈寒1 天前
为什么我的Vite热更新老是重新加载整个页面?
前端·人工智能·后端
一袋米扛几楼981 天前
【网络安全】SIEM -Security Information and Event Management 工具是什么?
前端·安全·web安全
小陈工1 天前
2026年4月7日技术资讯洞察:下一代数据库融合、AI基础设施竞赛与异步编程实战
开发语言·前端·数据库·人工智能·python
Cobyte1 天前
3.响应式系统基础:从发布订阅模式的角度理解 Vue2 的数据响应式原理
前端·javascript·vue.js