美文网首页
uniapp 网络请求的完整封装

uniapp 网络请求的完整封装

作者: coderhzc | 来源:发表于2022-08-30 11:03 被阅读0次

1. 在项目根目录创建一个service/baseService.js文件

// 基础配置
export const BASE_URL = "IP地址" // 本地测试环境 API 地址
export const BASE_URL_IMAHE = "IP地址" // 本地测试环境 图片 和视频 地址

// export const BASE_URL = "IP地址"; // 线上正式环境

// export const BASE_URL = "IP地址" // 线上正式环境 API 地址
// export const BASE_URL_IMAHE = "IP地址" // 线上正式环境 图片 和视频 地址

// 图片视频上传地址

class HZCRequest {
  request(url, method, params, header = {}) {
    const token = uni.getStorageSync("token")
    return new Promise((resolve, reject) => {
      uni.request({
        url: BASE_URL + url,
        method: method || "GET",
        header: {
          Authorization: "bearer " + token,
        },
        data: params,
        success: res => {
          // console.log(res);
          if (res.data.code === 2100) {
            uni.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 2000,
            })
            return uni.navigateTo({
              url: "../Login/Login",
            })
          }
          resolve(res.data)
        },
        fail: err => {
          // console.log(err);
          reject(err)
        },
      })
    })
  }

  get(url, params, header) {
    //判断是否有网络
    uni.getNetworkType({
      success: function (res) {
        if (res.networkType === "none") {
          uni.showToast({
            icon: "none",
            title: "网络异常,请检测网络配置!",
            duration: 2000,
          })
        }
      },
    })
    return this.request(url, "GET", params, header)
  }
  post(url, data, header) {
    //判断是否有网络
    uni.getNetworkType({
      success: function (res) {
        if (res.networkType === "none") {
          uni.showToast({
            icon: "none",
            title: "网络异常,请检测网络配置!",
            duration: 2000,
          })
        }
      },
    })
    return this.request(url, "POST", data, header)
  }
}

const hzcRequest = new HZCRequest()

export default hzcRequest

2. 每个单独的页面调用接口的话,在service/login/login.js文件,在单独的页面去写请求的数据接口封装:

import hzcRequest from "../baseService.js";

// 登录
export function getLoginInfo(data) {
  return hzcRequest.post("/api/User/Login", data);
}

3. 在页面使用:

<template>
  <view class="login-box">
    <view class="left">
      <view class="from-box">
        <image
          src="@/static/img/HOPPECKE.png"
          mode=""
          class="logo-style"
        ></image>
        <!-- 标题 -->
        <text class="title-style">设备维修系统</text>
        <!-- form表单 -->
        <view class="uni-form-items">
          <input
            type="text"
            class="uni-input"
            name="input"
            placeholder="请输入账号/邮箱"
            v-model="userInfo.UserAccount"
          />
        </view>

        <view class="uni-form-items">
          <input
            type="password"
            class="uni-input"
            name="password"
            placeholder="请输入密码"
            v-model="userInfo.UserPwd"
          />
        </view>

        <view class="uni-form-items m-t-20 radio-style-box">
          <radio-group name="radio" @change="radioChange">
            <label v-for="(item, index) of radioList" :key="item.id">
              <radio
                :value="item.value"
                :checked="index === current"
                style="#00654A"
              />
              <text
                class="p-r-20 f-20"
                :class="index === current ? 'active-color' : ''"
              >
                {{ item.title }}
              </text>
            </label>
          </radio-group>
        </view>

        <button
          form-type="submit"
          class="btn-default login"
          @click="LoginSubmit"
          :disabled="loginDisabled"
        >
          登录
        </button>
      </view>
    </view>
    <view class="right"><image src="@/static/c11.png" mode=""></image></view>
  </view>
</template>

<script>
import { getLoginInfo } from "../../service/login/login.js";
import startMonitoringNetWork from '../../utils/notework.js'
import md5 from "js-md5";
export default {
  data() {
    return {
      userInfo: {
        UserAccount: "",
        UserPwd: "",
        IsAD: 0,
      },
      radioList: [
        {
          id: 0,
          title: "邮箱用户",
          value: "0",
        },
        {
          id: 1,
          title: "AD域用户",
          value: "1",
        },
      ],
      current: 0,
      loginDisabled:false,
    };
  },
  mounted() {
    // this.$startMonitoringNetWork();
  },
  methods: {
    async LoginSubmit() {
      if (!this.userInfo.UserAccount || !this.userInfo.UserPwd) {
        return uni.showModal({
          title: "账户或密码不能为空!",
          position: "center",
          showCancel: false,
        });
      }
      try {
        if(!this.loginDisabled){
          this.loginDisabled = true;
          let resUserInfo = await getLoginInfo({
            UserAccount: this.userInfo.UserAccount,
            UserPwd: md5(this.userInfo.UserPwd),
            menuCode: 300001,
            IsAD: this.userInfo.IsAD,
          });
          if (resUserInfo.code === 1000) {
            if (resUserInfo.data.menus.length > 0) {
              setTimeout(() => {
                uni.reLaunch({
                  url: "../index/index",
                });
                this.loginDisabled = false;
                uni.showToast({
                  title: "登录成功",
                  duration: 2000,
                });
              }, 200);
              console.log(resUserInfo.data.token);
              uni.setStorageSync("token", resUserInfo.data.token);
              uni.setStorageSync("user_info", resUserInfo.data.user_info);
              uni.setStorageSync("menus", resUserInfo.data.menus);
              uni.setStorageSync("post", resUserInfo.data.post);
            } else {
              this.loginDisabled = false;
              return uni.showToast({
                title: "当前账号无登录系统权限!",
                icon: "none",
                duration: 2000,
              });
            }
          }
          if (resUserInfo.code === 2000) {
            this.loginDisabled = false;
            return uni.showToast({
              title: resUserInfo.msg,
              icon:'none',
              duration: 2000,
            });
          }
        } 
      } catch (error) {
        this.loginDisabled = false;
      }
    },
    // radio 按钮的逻辑实现
    radioChange: function (evt) {
      for (let i = 0; i < this.radioList.length; i++) {
        if (this.radioList[i].value === evt.detail.value) {
          this.current = i;
          this.userInfo.IsAD = i;
          break;
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.login-box {
  display: flex;
  width: 100%;
  .active-color {
    color: #00654a;
  }
  .left {
    width: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fff;
    height: 100vh;
    .from-box {
      width: 100%;
      .logo-style {
        width: 155.85937rpx;
        height: 31.64062rpx;
        margin-left: 30%;
      }
      .title-style {
        color: #000000;
        display: inline-block;
        width: 100%;
        font-size: 21.09375rpx;
        text-align: center;
        font-weight: 900;
        line-height: 19.92187rpx;
      }

      .radio-style-box {
        margin-left: -26.50781rpx;
      }
      .login {
        font-size: 14rpx;
      }
    }
  }
  .right {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    image {
      width: 335.74218rpx;
      height: 259.57031rpx;
    }
  }
  .uni-form-items {
    width: 100%;
    display: flex;
    justify-content: center;
    .uni-input {
      margin-top: 16rpx;
      width: 192.1875rpx;
      height: 24.60937rpx;
      font-size: 10.54687rpx;
      padding-left: 8.20312rpx;
      border: 0.58593rpx solid #00674b;
      border-radius: 2.34375rpx;
    }
  }
  button::after {
    border: none;
  }
}
</style>

实际截图

image.png

相关文章

网友评论

      本文标题:uniapp 网络请求的完整封装

      本文链接:https://www.haomeiwen.com/subject/htelnrtx.html