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

发布于:2025-06-03 ⋅ 阅读:(27) ⋅ 点赞:(0)

HBuilder X v4.66 当前最新版本

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

封装方法

// 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);
			}
		})
	})
}

如下使用:

<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>


网站公告

今日签到

点亮在社区的每一天
去签到