123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- // uni-app请求封装
- export default class Request {
- static loadingCount = 0;
- static excludePaths = []; // 排除的路径列表
- static excludePages = []; // 排除的页面列表
-
- // 添加排除路径(支持正则表达式)
- static addExcludePath(path) {
- this.excludePaths.push(path);
- }
-
- // 添加排除页面(页面路径)
- static addExcludePage(page) {
- this.excludePages.push(page);
- }
-
- // 检查当前页面是否在排除列表中
- static isCurrentPageExcluded() {
- const pages = getCurrentPages();
- if (pages.length === 0) return false;
-
- const currentPage = pages[pages.length - 1];
- const route = currentPage.route || currentPage.__route__;
-
- return this.excludePages.some(excludePage =>
- route.includes(excludePage) || excludePage.includes(route)
- );
- }
-
- // 检查路径是否在排除列表中
- static isPathExcluded(path) {
- return this.excludePaths.some(excludePath => {
- if (excludePath instanceof RegExp) {
- return excludePath.test(path);
- }
- return path.includes(excludePath) || excludePath.includes(path);
- });
- }
-
- http(router, data = {}, method, contentType, showLoading = true) {
- let that = this;
- let path = 'https://live.test.ylrztop.com/live-api'; // 余红奇
- // let path = 'http://192.168.10.166:7114'; // 余红奇
-
- // 检查是否应该显示loading
- const shouldShowLoading = showLoading &&
- !Request.isPathExcluded(router) &&
- !Request.isCurrentPageExcluded();
-
- // 只在第一个请求且需要显示loading时显示
- if (shouldShowLoading && Request.loadingCount === 0) {
- uni.showLoading({
- title: '加载中',
- mask: true
- });
- }
-
- if (shouldShowLoading) {
- Request.loadingCount++;
- }
-
- return new Promise((resolve, reject) => {
- let token = uni.getStorageSync('AppToken');
- var httpContentType = 'application/x-www-form-urlencoded';
-
- if (contentType != undefined) {
- httpContentType = contentType;
- }
-
- uni.request({
- header: {
- 'Content-Type': httpContentType,
- 'AppToken': token
- },
- url: `${path}${router}`,
- data: data,
- method: method,
- success: (res) => {
- if (res.code == 401) {
- let pages = getCurrentPages();
- let url = pages[pages.length - 1];
-
- if (url != undefined && url.route == "/pages/home/index") {
- resolve(res.data)
- return;
- }
-
- uni.reLaunch({
- url: '/pages/home/index'
- });
- return;
- }
-
- if (res.token) {
- uni.setStorageSync('AppToken', res.token)
- }
-
- resolve(res.data)
- },
- fail: (res) => {
- reject(res);
- },
- complete: (res) => {
- // 只有需要显示loading的请求才减少计数器
- if (shouldShowLoading) {
- Request.loadingCount--;
-
- if (Request.loadingCount <= 0) {
- uni.hideLoading();
- Request.loadingCount = 0;
- }
- }
- }
- })
- })
- }
- }
|