uni-app: implements the recursion of the request request (setting the number of visits to the request request), and calls a custom method to give the return value

1. Effect display

failure effect

successful effect

2. Write the backend request part

analyze

① Customize a module common.js mainly to encapsulate all request functions

②Core code
function requestWithRetry(cmd, username, password, retryCount) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: ip + 'sys/user/login',
			data: {
				cmd: cmd,
				usrname: username,
				passwd: password
			},
			method: 'POST',
			dataType: 'json',
			header: {
				"content-type": "application/json"
			},
			success: res => {
				// 存入全局变量中
				getApp().globalData.username = username;
				getApp().globalData.password = password;
				getApp().globalData.access_token = res.data.access_token;
				getApp().globalData.loginmode = loginmode;
				console.log(`第 ${retryCount} 次请求成功:`, res.data);
				resolve(res.data);
			},
			fail(err) {
				console.error(`第 ${retryCount} 次请求失败,剩余重试次数 ${retryCount - 1}:`, err)
				if (retryCount <= 1) {
					// 重试次数已经用完,将错误信息返回给调用者
					reject(new Error('请求失败'))
				} else {
					// 还有重试次数,继续重试
					setTimeout(() => {
						requestWithRetry(cmd, username, password,
							retryCount - 1).then(resolve).catch(reject)
					}, 500)
				}
			}
		});
	});
}
// 调用方法,retryCount 为重试次数
return requestWithRetry(cmd, username, password, 3)
	.then(data => {
		// console.log('请求成功', data);
		return data;
	})
	.catch(error => {
		// console.log('请求失败', error);
		throw error;
	});


Complete code

//定义全局变量
const ip = 'XXXX';
//定义全局函数
//生成随机三位数 
function generateRandomNumber() {
	var min = 100;
	var max = 999;
	var randomNumber = Math.floor(Math.random() * (max - min + 1) + min);
	return randomNumber;
}
//http方式进行登录
function login_httpmode(username, password, cmd, loginmode) {
    //http
    if (loginmode == 'http') {
        function requestWithRetry(cmd, username, password, retryCount) {
            return new Promise((resolve, reject) => {
                uni.request({
                    url: ip + 'sys/user/login',
                    data: {
                        cmd: cmd,
                        usrname: username,
                        passwd: password
                    },
                    method: 'POST',
                    dataType: 'json',
                    header: {
                        "content-type": "application/json"
                    },
                    success: res => {
                        // 存入全局变量中
                        getApp().globalData.username = username;
                        getApp().globalData.password = password;
                        getApp().globalData.access_token = res.data.access_token;
                        getApp().globalData.loginmode = loginmode;
                        console.log(`第 ${retryCount} 次请求成功:`, res.data);
                        resolve(res.data);
                    },
                    fail(err) {
                        console.error(`第 ${retryCount} 次请求失败,剩余重试次数 ${retryCount - 1}:`, err)
                        if (retryCount <= 1) {
                            // 重试次数已经用完,将错误信息返回给调用者
                            reject(new Error('请求失败'))
                        } else {
                            // 还有重试次数,继续重试
                            setTimeout(() => {
                                requestWithRetry(cmd, username, password,
                                    retryCount - 1).then(resolve).catch(reject)
                            }, 500)
                        }
                    }
                });
            });
        }
        // 调用方法,retryCount 为重试次数,设置最大次数为三次
        return requestWithRetry(cmd, username, password, 3)
            .then(data => {
                // console.log('请求成功', data);
                return data;
            })
            .catch(error => {
                // console.log('请求失败', error);
                throw error;
            });
    }
}
//导出
module.exports = {
	ip,
	generateRandomNumber,
	login_httpmode,
}

3. Call the method

core code

common.login_httpmode(username, password, cmd, type)
	.then(info => {
		console.log("请求成功",info)		
	})
	.catch(error => {
		console.log("请求失败",error)		
	});

Complete code

//执行加载中的效果
uni.showLoading({
	title: '正在登录...',
	mask: true,
});
//调用登录方法
common.login_httpmode(username, password, cmd, type)
     //成功返回
	.then(info => {
		console.log("请求成功",info)
		if (info.success == true) {	
            uni.hideLoading(); // 隐藏加载提示
			//全局变量中的数据 
			uni.reLaunch({ //跳转到主页
				url: '/pages/mine/mine_index/mine_index'
			})
		} else {
			uni.hideLoading(); // 隐藏加载提示
			if (info.msg == 'pass err') {
				uni.showToast({
					title: '账号密码不正确',
					icon: 'none'
				})
			}
		}
	})
	.catch(error => {
		console.log("请求失败",error)
		uni.showToast({
			title: '登录失败',
			icon: 'none'
		})
	});

Guess you like

Origin blog.csdn.net/weixin_46001736/article/details/134527043