uniapp封装请求

该文章展示了如何在uni-app中封装http请求,包括设置基础URL,处理请求头,错误处理(如401、403错误),以及登录状态过期后的重新登录逻辑。此外,还涉及到本地存储中的token获取和使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import config from './profile.js'
const BASE_URL = config.baseURL; //接口地址
export const http = (options, ) => {
	const token = uni.getStorageSync('token');
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '处理中...',
			mask: true
		})
		uni.request({
			url: BASE_URL + options.url,
			method: options.method || 'GET',
			data: options.data || {},
			header: options.method == 'GET' ? {
				'token': token,
				'Content-Type': 'application/json; charset=UTF-8',
				'X-Requested-With': 'XMLHttpRequest',
			} : {
				'token': token,
				'X-Requested-With': 'XMLHttpRequest',
				'Content-Type': 'application/json; charset=UTF-8'
			},
			dataType: 'json',
			success: (res) => {
				uni.hideLoading();
				if (res.data.code == "00401") {
					uni.showModal({
						title: '提示',
						content: '账号已过期,请重新登录',
						cancelText: "取消", // 取消按钮的文字  
						confirmText: "确认", // 确认按钮的文字  
						showCancel: false, // 是否显示取消按钮,默认为 true
						success: (res) => {
							if (res.confirm) {
								uni.reLaunch({
									url: '/pages/login/index'
								});
								console.log('comfirm') //点击确定之后执行的代码
							} else {
								console.log('cancel') //点击取消之后执行的代码
							}
						}
					})
				};
				console.log(res.statusCode)
				switch (res.statusCode) {
					case 200:
                         resolve(res);
					    break;
					case 401:
						uni.showToast({
							icon: 'none',
							title: '未授权',
							duration: 2000
						})
                        break;
                    case 403:
							uni.showToast({
								icon: 'none',
								title: '登录身份失效,请重新登录',
								duration: 2000
							})
						break;
					case 405:
							uni.showToast({
								icon: 'none',
								title: '请求方法错误',
								duration: 1500
							})
						break;
                    default:
							uni.showToast({
								icon: 'none',
								title: '请求错误:' + res.statusCode,
								duration: 1500
							})
						break;
				}
			},
			fail: (err) => {
				console.log('request fail data', data)
				console.log('request fail err', err.errMsg + '  ' + method + '  ' + baseUrl +
					url)
				uni.showToast({
					icon: 'none',
					title: '请求失败,请稍后再试',
					duration: 2000
				});
				reject(err);
			}
		})
	})
}

使用

	import {
		http
	} from "../../utils/request.js"


				http({
					url: '/api/member/patientcard/findPatientCard',
					method: 'GET',
					data: {
						organId: uni.getStorageSync('organId'),
					}
				}).then(res => {
					this.patientCard = res.data.patientCard;
					// this.patientCard = res.data.patientCard;
				})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值