uniapp 如何封装uni.request请求(登录接口、业务接口)

一、新建目录

根目录下新建util(文件/文件夹名字随意)文件夹,下面新建request.js请求;

二、util/request.js文件夹内容 

 这个是一个登录功能的请求接口,请求的header大家根据实际情况来写

/**
 * @param { url } 接口地址
 * @param { method } 请求方式
 * @param { data } 请求参数
 * @param { header } 请求头/token/cookie
 * @param { hideLoading }  显示加载动画
 * @dataType 解析为JSON
 * 
 */

import Vue from 'vue';
var _this = Vue.prototype


const baseURL = "http://192.168.0.31:8080"


const request = (options) => {
	var hideLoading = options.hideLoading || false;
	const language = uni.getStorageSync('language') ?? 'zh-HK'; //多语言
	const cookie = 'xxxxx'; // 自己需要携带的Cookie内容
	if (!hideLoading) {
		uni.showLoading({
			title: _this.l('Loading'), // 这是我们的多语言写法
		})
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: baseURL + options.url,
			method: options.method || "GET",
			data: options.data || {},
			header: {
				'content-Type': 'application/json;charset=UTF-8',
				'UxSoft.Localization.CultureName': language, // 自定义请求头
				Cookie: cookie,
				token: uni.getStorageSync('userToken') ?? '',
			},
			dataType: 'json',
			success: res => {
				if (res.data.code === 403) {
					let userInfo = uni.getStorageSync('userInfo'),	
						password = uni.getStorageSync('password'),
						phoneNumber = uni.getStorageSync('phoneNumber'),
						phoneAreaCode = uni.getStorageSync('phoneAreaCode');
					if (userInfo  && password &&
						phoneNumber && phoneAreaCode) {
						_this.$request({
							url: '/app/VipUserController/login',
							method: 'GET',
							hideLoading: true,
							data: {
								password: password,
								phoneNumber: phoneNumber,
								phoneAreaCode: phoneAreaCode
							}
						}).then(res => {
							let routes = getCurrentPages() || [];
							let currentRoute = routes[routes.length - 1]
							if (res.data.result && res.data.result.token) {
								uni.setStorageSync('userToken', res.data.result.token);
								if (currentRoute) {
									uni.reLaunch({
										url: currentRoute.$page.fullPath,
										success(s) {
											console.log('登录重定向成功:', s)
										},
										fail(e) {
											console.log('登录重定向失败:', e)
										}
									})
								} else {
									uni.reLaunch({
										url: '/platforms/mp-weixin/mine/mine'
									})
								}
							} else {
								uni.showModal({
									title: _this.l('Tips'),
									content: res.data.error,
									showCancel: false,
									success: function(res) {
										uni.removeStorageSync('userInfo');
										uni.reLaunch({
											url: '/platforms/mp-weixin/discount/discount'
										})
									}
								});
							}
						}).catch(err => console.log('重新登陆错误:', err))
					} else {
						uni.showToast({
							title: _this.l('LoginExpiration'),
							icon: 'none',
							duration: 3000,
						});
						uni.removeStorageSync('userInfo');
						setTimeout(() => {
							uni.reLaunch({
								url: '/platforms/mp-weixin/discount/discount'
							})
						}, 3000)
						return;
					}
					reject();
				} else {
					resolve(res)
				}
			},
			fail: (err) => {
				reject(err)
			},
			complete: () => {
				if (!hideLoading) {
					uni.hideLoading()
				}
				resolve();
				return;
			}
		})
	})
}

export {
	baseURL,
	request
}

三、在 api 文件夹下 mine 模块导入 request

Tips: 注意导入方式  { request }

import {
	request
} from "@/util/request.js"

// 获取用户 积分
export function countTotalPoint(data) {
	return request({
		url: '/app/VipPointLog/countTotalPoint',
		method: 'POST',
		hideLoading: false,
		data: data
	})
};

// 刷新用户信息
export function miniProgramMemberInfo(data) {
	return request({
		url: '/app/VipUserController/miniProgramMemberInfo',
		method: 'POST',
		hideLoading: true,
		data: data
	})
};

四、在页面使用

mine 页面

import { countTotalPoint, miniProgramMemberInfo } from '@/api/mp-weixin/mine/mine.js';


//refresh userInformation
refreshUserInformation() {
	miniProgramMemberInfo({ id: uni.getStorageSync('vipCardId') }).then(result => {
		if (!result.data.result) {
			return;
		}
		let user = result.data.result;
		uni.setStorageSync('userInfo', user);
		this.$setCompanyName(user.vipCardList[0].companyRegionCode);
	});
}

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Iam_楠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值