【微信小程序篇】-请求封装

最近自己在尝试使用AIGC写一个小程序,页面、样式、包括交互函数AIGC都能够帮我完成(不过这里有一点问题AIGC的上下文关联性还是有限制,会经常出现对于需求理解跑偏情况,需要不断的重复强调,并纠正错误,才能得到你想要的内容)。

因为最近某些原因,所处的环境网络没办法科学上网,剩下的网络交互需要自己完成。

请求封装

常用的请求方式:POST、GET
了解了一些网友们封装的方式,使用 Promise 来完成,Let’s do it。

1.动态配置环境:

env.config.js

const envConf = {
    //本地环境
    develop: {
        mode: 'dev',
        DEBUG: false,
        VCONSOLE: true,
        appid: '***',
        VUE_APP_BASE_URL: 'https://***',
    },
    //测试环境
    test: {
        mode: 'test',
        DEBUG: false,
        VCONSOLE: false,
        appid: '***',
        VUE_APP_BASE_URL: 'https://***',
    },
    //开发环境
    prod: {
        mode: 'prod',
        DEBUG: false,
        VCONSOLE: false,
        appid: '***',
        VUE_APP_BASE_URL: 'https://***',
    }
}
module.exports = {
    // 获取 envVersion是true的环境
    env: envConf[__wxConfig.envVersion]
}

2.封装请求

第一部分:基本信息处理

基本的环境信息及用户、租户、信息获取,不需要token的请求地址配置,需要统一处理code的数组配置

const app = getApp();
var tokenKey = "token";
var login_path = '/pages/login/login';
//请求url;引用的是env.config.js中对应环境的
var serverUrl = env.env.VUE_APP_BASE_URL;
var userInfo = wx.getStorageSync('userInfo');
var tenantid = '1'; //租户Id
if (!userInfo === '') {
	tenantid = userInfo.relTenantIds.split(',')[0];
}
import env from '../config/env.config'
// 例外不用token的地址
var exceptionAddrArr = ['/sys/login', ];
// 跳转到登录页的 code
var jumpLoginCodes = [
    1001,
    1002,
    1007,
    1009,
    1010,
]

第二部分:请求头设置

//请求头处理函数
function CreateHeader(url, type) {
	let header = {}
	if (type == 'POST_PARAMS') {
		header = {
			'content-type': 'application/x-www-form-urlencoded',
		}
	} else {
		header = {
			'content-type': 'application/json',
		}
	}
	if (exceptionAddrArr.indexOf(url) == -1) {
		//排除请求的地址不需要token的地址
		let token = wx.getStorageSync(tokenKey);
		// header.Authorization = token;
		//请求头携带token还有租户id
		header['X-Access-Token'] = token;
		header['tenant-id'] = tenantid;
	}
	return header;
}

第三部分:请求封装

POST请求部分
//post请求,数据在body中
function postRequest(url, data) {
	let header = CreateHeader(url, 'POST');
	return new Promise((resolve, reject) => {
		wx.request({
			url: serverUrl + url,
			data: {
				...data,
				tenantId: tenantid
			},
			header: header,
			method: 'POST',
			success: (res => {
				if (res.statusCode === 200 && res.data && res.data.code === 200) {
					resolve(res)
				}
				//Token失效  跳转至登录页面
				else if (res.data && jumpLoginCodes.indexOf(res.data.code) > -1) {
					//移除失效token
					wx.removeStorageSync('token')
					//移除失效的用户信息
					wx.removeStorageSync('userInfo')
					//属于tabbar的页面,只能通过wx.switchTab来跳转
					// wx.switchTab({
					// 	url: login_path,
					// }) 
					// 不属于 tabbar 的页面,需要通过 wx.navigateTo 来跳转
                    wx.navigateTo({
                        url: login_path
                    });
					console.log("TOKEN失效");
					wx.showToast({
						icon: "none",
						title: (res.data && res.data.message) || "请求失败",
					});
				} else {
					wx.showToast({
						icon: "none",
						title: (res.data && res.data.message) || "请求失败",
					});
					reject(res)
				}
				setTimeout(_ => {
					wx.hideLoading();
				}, 500)
			}),
			fail: (res => {
				wx.hideLoading();
				console.log("err!!!!", err) wx.showToast({
					icon: "none",
					title: '请求失败',
				});
				reject(err)
			})
		})
	})
}
//post请求,数据按照query方式传给后端
function postParamsRequest(url, data) {
	let header = CreateHeader(url, 'POST_PARAMS');
	let useurl = url;
	console.log(useurl);
	return new Promise((resolve, reject) => {
		wx.request({
			url: serverUrl + useurl,
			header: header,
			method: 'POST',
			success: (res => {
				if (res.statusCode === 200 && res.data && res.data.code === 200) {
					resolve(res)
				}
				//Token失效  跳转至登录页面
				else if (res.data && jumpLoginCodes.indexOf(res.data.code) > -1) {
					//移除失效的用户信息
					wx.removeStorageSync('userInfo')
					//移除失效token
					wx.removeStorageSync('token')
					//属于tabbar的页面,只能通过wx.switchTab来跳转
					// wx.switchTab({
					// 	url: login_path,
					// }) 
					// 不属于 tabbar 的页面,需要通过 wx.navigateTo 来跳转
                    wx.navigateTo({
                        url: login_path
                    });
					wx.showToast({
						icon: "none",
						title: (res.data && res.data.message) || "请求失败",
					});
				} else {
					wx.showToast({
						icon: "none",
						title: (res.data && res.data.message) || "请求失败",
					});
					reject(res)
				}
				setTimeout(_ => {
					wx.hideLoading();
				}, 500)
			}),
			fail: (res => {
				wx.hideLoading();
				console.log("err!!!!", err) wx.showToast({
					icon: "none",
					title: '请求失败',
				});
				reject(err)
			})
		})
	})
}
GET请求部分
//get 请求
function getRequest(url, data) {
	let header = CreateHeader(url, 'GET');
	return new Promise((resolve,
		reject) => {
		wx.request({
			url: serverUrl + url,
			data: data,
			header: header,
			method: 'GET',
			success: (
				res => {
					//统一处理响应状态码
					if (res.statusCode === 200 && res.data && res.data.code === 200) {
						resolve(res)
					}
					//Token失效  跳转至登录页面
					else if (res.data && jumpLoginCodes.indexOf(res.data.code) > -1) {
						//移除失效的用户信息
						wx.removeStorageSync('userInfo')
						//移除失效token
						wx.removeStorageSync('token')
						//属于tabbar的页面,只能通过wx.switchTab来跳转
					    // wx.switchTab({
						// 	url: login_path,
						// }) 
						// 不属于 tabbar 的页面,需要通过 wx.navigateTo 来跳转
                    	wx.navigateTo({
                    	    url: login_path
                    	});
						wx.showToast({
							icon: "none",
							title: (res.data && res.data.message) || "请求失败",
						});
					} else {
						wx.showToast({
							icon: "none",
							title: (res.data && res.data.message) || "请求失败",
						});
						reject(res)
					}
					setTimeout(_ => {
						wx.hideLoading();
					}, 500)
				}),
			fail: (res => {
				wx.hideLoading();
				console.log("err!!!!", err) wx.showToast({
					icon: "none",
					title: '请求失败',
				});
				reject(err)
			})
		})
	})
}

参考部分别人的内容,自己做了一些适合自己的判定改造,搞定。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
微信小程序中的请求地址封装一般有以下几种方式: 1. 直接使用原生的wx.request()方法,将请求地址直接写在其中。这种方式比较简单,但是在多个地方都需要请求同一个地址时,会导致代码重复,不易维护。 2. 在app.js中定义全局变量,存储请求地址,然后在需要发送请求的页面中引入app.js,在请求时使用全局变量中的地址。这种方式可以避免代码重复,但是在需要请求多个地址时,需要定义多个全局变量,会导致代码臃肿。 3. 封装一个工具类,将请求地址作为参数传入封装好的方法中。这种方式可以解决以上两种方式的问题,可以在工具类中定义多个请求地址,在需要发送请求时,只需要传入对应的地址即可。 下面是一个简单的请求地址封装示例: ```javascript // 工具类 request.js const BASE_URL = 'https://example.com/api/' function request(url, data, method = 'GET') { return new Promise((resolve, reject) => { wx.request({ url: BASE_URL + url, data, method, success: res => { resolve(res.data) }, fail: err => { reject(err) } }) }) } export default request ``` 使用时,在需要发送请求的页面中引入request.js,然后调用封装好的request方法即可: ```javascript import request from './request.js' // 发送 GET 请求 request('users', { id: 1 }).then(res => { console.log(res) }) // 发送 POST 请求 request('users', { name: 'John' }, 'POST').then(res => { console.log(res) }) ``` 以上示例中,BASE_URL为请求地址的公共部分,request方法接受三个参数,其中url为请求地址的相对路径,data为请求参数,method为请求方法,默认为GET。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

夜七天

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

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

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

打赏作者

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

抵扣说明:

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

余额充值