uniapp小程序发送请求(封装方法)

//operate.js文件内容
//export const api = 'http://192.168.0.7:8080/'
import {
	api
} from "@/utils/operate.js";
export default class Request {
	http(param) {
		// 请求参数
		let url = param.url,
			method = param.method,
			header = {},
			data = param.data || {},
			hideLoading = param.hideLoading || false;

		//拼接完整请求地址
		let requestUrl = api + url;

		//请求方式:GET或POST(POST需配置
		header: {
			'content-type',
			"application/json"
		}
		//加载圈
		if (!hideLoading) {
			uni.showLoading({
				title: "加载中...",
				mask: true
			});
		}

		// 返回promise
		return new Promise((resolve, reject) => {
			// 请求
			uni.request({
				url: requestUrl,
				data: data,
				method: method,
				header: header,
				success: res => {
					// 判断 请求api 格式是否正确
					if (res.statusCode && res.statusCode != 200) {
						uni.showToast({
							// 这是后端返回的错误信息
							title: "api错误" + res?.errMsg ?? '未知错误',
							icon: "none"
						});
						reject(res.data)
						return;
					}
					if (res.data.code != 0) {
						console.log('res.data.code不等于0', res);
						uni.showToast({
							// 这是后端返回的错误信息
							title: res.data?.msg ?? '未知错误',
							icon: "none"
						});
						reject(res.data)
						return
					}
					// 将结果抛出
					resolve(res.data);
				},
				//请求失败
				fail: e => {
					let flag = true
					uni.getNetworkType({
						success: res => { //网络类型 wifi、2g、3g、4g、ethernet、unknown、none
							if (res.networkType === 'none') {
								uni.showToast({
									title: e.data?.msg ?? '无网络',
									icon: "none"
								});
								reject(e.data);
							} else {
								uni.showToast({
									title: e.data?.msg ?? '未知错误',
									icon: "none"
								});
								reject(e.data);
							}
						}
					});

				},
				//请求完成
				complete() {
					//隐藏加载
					if (!hideLoading) {
						uni.hideLoading();
					}
					resolve();
				}
			});
		});
	}
}




Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐