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

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

一、新建目录

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

20210527153548522.png

二、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月前
uniApp常用功能封装
uniApp常用功能封装
32 0
uniapp简单的登录页面布局
uniapp简单的登录页面布局
|
2月前
|
移动开发 前端开发 JavaScript
uniapp中IO模块(管理本地文件系统)的常用功能封装
uniapp中IO模块(管理本地文件系统)的常用功能封装
124 1
|
2月前
|
缓存 JSON 安全
【Uniapp 专栏】Uniapp 与后端接口对接的实战要点
【5月更文挑战第12天】在 Uniapp 项目开发中,成功对接后端接口至关重要。要点包括:深入理解后端提供的接口文档,确保数据格式(如 JSON)正确处理,选择合适的请求方式(如 GET、POST),设置正确的请求头,做好错误处理和数据缓存策略,确保安全性(如使用 HTTPS 和令牌验证)并进行全面测试。同时,进行版本管理和团队协作,与后端开发人员保持良好沟通,以实现高效、稳定的接口对接。
|
2月前
|
SQL 开发框架 数据库连接
uniapp中sqlite数据库常用操作的简单封装
uniapp中sqlite数据库常用操作的简单封装
|
2月前
|
前端开发
uniapp 实现退出登录 清除Token
uniapp 实现退出登录 清除Token
125 0
|
2月前
|
API
uniapp怎么实现授权登录
uniapp怎么实现授权登录
99 2
|
2月前
|
前端开发 小程序 JavaScript
uniapp api uni.request讲解
uniapp api uni.request讲解
219 1
|
2月前
|
API
uniApp封装请求
uniApp封装请求
25 0
|
2月前
|
前端开发
uniapp如何封装接口
uniapp如何封装接口
68 0